Spring 3 JavaConfig Annotation Example

9 Flares Twitter 0 Facebook 1 Google+ 8 LinkedIn 0 Filament.io 9 Flares ×

Starting with Spring 3, JavaConfig features are included in the spring core modules. This allows programmers to move Bean definition and spring configuration information from the XML files to Java files. You are free to use the XML configuration as before if you want it that way. The choice is left to the developers.

The Core artifact is @Configuration annotated class.  Annotating a class with @Configuration indicates to Spring that this class holds the bean definitions. The bean definitions are specified using methods annotated with @Bean. A Spring application can use a single @Configuration annotated class or many. Using multiple such helps in modular configuration code. To declare a bean, provide a method with @Bean annotation. During Container initialization spring will execute the method and use the return type as a bean with the bean factory.  This is indicated by the example below via the orderService() method. You can also see how easy it is to define dependencies. The order bean has dependency with the User Bean. This dependency is defined simply as a method call to getUser() from the orderService() method. Bottom line is – dependency is as simple as one bean method calling another bean method.

Handling Callbacks

It is also pretty easy to get call back events during different phases of bean creation life cycle. For instance the @Bean annotation takes extra parameters to configure the post and pre-initialization call backs.

 Example – XML Configuration to JavaConfig

XML Configuration

Annotation Configuration: JavaConfig

@Configuration annotation informs Spring that this is the core Spring configuration file. Bean definitions can be specified using the @Bean annotation.

Bean Source Code


Spring JavaConfig

  • Aurélien Leboulanger

    is JavaConfig annotations are more efficient/performant than the XML configuration ?

  • ideally there shouldnt be any noticable difference.i havent compared these two from a performance standpoint.i will do a performance benchmark and see whether there are any impact on the application startup times. few posts on stackoverflow.com points to a little longer startup times with javaconfig when there are a lot of beans.