Spring JavaConfig is a product of the Spring community that provides a pure-Java approach to configuring the Spring IoC Container. While JavaConfig aims to be a feature-complete option for configuration, it can be (and often is) used in conjunction with the more well-known XML-based configuration approach.
See Section 8.1, “JavaConfig and XML” for more information on using JavaConfig and XML together
The Spring IoC Container is the leading dependency injection framework. It provides sophisticated dependency injection capabilities as well as advanced features for aspect-oriented programming. Today the majority of Spring users configure the Spring container using XML. This works very well, and in many cases is ideal. However, some developers find configuring the Spring container via Java a more natural or appropriate approach, for a variety of reasons.
Motivations of JavaConfig include:
Object-oriented configuration. Because configurations are defined as classes in JavaConfig,
users can take full advantage of object-oriented features in Java.
One configuration class may subclass another, overriding its
@Bean
methods, etc.
Reduced or eliminated XML configuration. The benefits of externalized configuration based on the principles of dependency injection have been proven. However, many developers would prefer not to switch back and forth between XML and Java. JavaConfig provides developers with a pure-Java approach to configuring the Spring container that is conceptually similar to XML configuration. It is technically possible to configure the container using only JavaConfig configuration classes, however in practice many have found it ideal to mix-and-match JavaConfig with XML. See Section 8.1, “JavaConfig and XML” for details.
Type-safe and refactoring-friendly. JavaConfig provides a type-safe approach to configuring the Spring container. Thanks to Java 5.0's support for generics, it is now possible to retrieve beans by type rather than by name, free of any casting or string-based lookups. See Section 4.3.2.1, “Type-safe access” for details.
JavaConfig takes full advantage of Java 5.0 language features, especially annotations and generics. A Java 5.0+ runtime environment is a requirement for using JavaConfig.. For an introduction to annotations and other Java 5.0 features, see http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html and http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html#lang
Every effort has been made to reduce the number of dependencies Spring JavaConfig requires. For very simple configurations, the dependencies are limited to CGLIB, commons-logging, spring-core, spring-beans, and spring-context. If you use more advanced features such as AOP, you'll need aspectj, spring-aop, etc. Maven2 use is recommended, as it helps greatly in reducing the burden of dependency management.
See also: Appendix C, Maven2 POM configurations