Configure Spring without XML

Rod Johnson - one of the Spring developers - wrote about the upcoming Java configuration option for Spring beans.

@Configuration
public class NoXMLConfig {
  @Bean
  public Address address() {
    return new Address();
  }

  @Bean
  public Person person() {
    Person person = new Person();
    person.setLocation(address());
    return person;
  }
}

This will create two beans of types Address and Person and then insert the Address bean into Person by calling the setter setLocation(). In XML it would look like this:

<bean id="address" class="Address"/>

<bean id="person" class="Person">
	<property name="location" ref="address"/>
</bean>

If you don't like to configure your code in an XML file, you might fall in love with this more programmatic approach right in your Java code. The interesting part is that the Java class - NoXMLConfig in the example - that creates the beans (it's a bean factory after all) can use any additional logic you can dream of. So you might create beans conditionally, if you need to.




Add a comment Send a TrackBack