Summary
In a recent blog post, Rod Johnson introduces a new developer-friendly configuration option for Spring applications. While not intended to replace Spring's XML-based configuration, the new option defines configuration in Java classes in what Johnson describes as a mini configuration DSL.
Complex applications require multiple types of configuration and Spring aims to provide the best overall solution for configuration.
In keeping with that promise, Johnson introduces a new, annotation-based option to configure Spring applications. This method, currently available as a separate package, is not meant to replace Spring's XML-based configuration, only to provide a more programmer-friendly alternative:
Although it is based on annotations, [the Spring] Java config mechanism is unique in uses of annotations... Annotations are not included in the core business logic, but in separate configuration classes. Effectively, it's a DSL for configuration. So it retains the non-invasive promise of Spring: you don't need to change your Java code to use it.
Johnson introduces class-based annotation by contrasting it to how a similar configuration would be achieved with XML configuration files:
With the @Configuration and @Bean annotations, the same effect could be defined as follows:
@Configuration
public class MyConfig {
@Bean
public Person rod() {
return new Person("Rod Johnson");
}
@Bean(scope = Scope.PROTOTYPE)
public Book book() {
Book book = new Book("Expert One-on-One J2EE Design and Development");
book.setAuthor(rod()); // rod() method is actually a bean reference !
return book;
}
}
Johnson notes that using a Java class for configuration offers several benefits:
Every @Bean is a Spring component and can take advantage of all Spring services, such as declarative transaction management.
Every public @Bean method is added to the Spring container, so it's eligible for injection into other objects, JMX export and other benefits.
It fits smoothly into an existing Spring environment.
Johnson also adds that since each configuration class is defined as Java code, configuration classes can be refactored inside an IDE.
In the conclusion of his post, Johnson notes that developers will most likely use both XML and class-based configuration in real-world applications. While many widely-used enterprise tools, such as the Java Persistence API (JPA) or Hibernate, allow annotation-based configuration, few tools go so far in defining a configuration DSL as the new Spring configuration option does.
In your projects, how do you decide between XML-based and class-based—including annotation-based—configuration?