Annotation-based Spring Configuration

Spring has been supporting annotation-based context configuration for some years now. Time to explore it if you haven’t already done so! A quick overview is available here. Getting rid of your XML configuration is as easy as:

@Configuration
public class MyContext {
    // Reference to a bean defined somewhere else
    @Autowired SomeBean someBean;

    @Bean
    public OtherBean otherBean() {
        return new OtherBean(someBean);
    }

    // A bean referencing another bean in this context
    @Bean AnyBean anyBean() {
        return new AnyBean(otherBean());
    }
}

If you need to reference a specific bean using @Autowired, you can use @Qualified to reference a bean by name:

    // Reference to a specific bean defined somewhere else
    @Autowired @Qualifier("someSpecificBean")
    SomeBean someBean;

Then, somewhere in your application’s bootstrap code, load the context. In a Web App, load the @Configuration-annotated class using a ContextListener as you would with a XML context configuration.

ApplicationContext context = new AnnotationConfigApplicationContext(MyContext.class);
context.refresh();

Another possibility is to use classpath scanning to pick up your annotated beans, contexts, controllers, …:

ApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("my.base.package");
context.refresh();

That’s it! You get a context configuration in pure Java source code that’s easy to navigate and refactor in any IDE of your choice.

If you want to load a context in a test case using @ContextConfiguration, you’ll have to resort to a custom ContextLoader implementation (see here) until SPR-6184 is fixed.

Advertisements
This entry was posted in Java, Spring. Bookmark the permalink.

One Response to Annotation-based Spring Configuration

  1. Ben says:

    Thanks for this post… SPR-6184 has been fixed now

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s