Look Ma, no XML! How to use annotations to eliminate declarations in XML.

In Spring 2.1 you no longer need to explicitly register your beans with Spring using <bean> tags in the Spring XML file. Spring 2.1 allows you to specify a java package where your beans live and it will scan for all the beans in that package and automatically register them for you. How does it know which classes are beans? You guessed it: class annotations. Any class annotated with @Component, @Repository or @Aspect will automatically get picked up by Spring.

Further, any fields within those classes that need to get injected just need to be annotated with the @Autowired field/setter annotation. Or if they need context themselves for more involved lookups (e.g. with derived names) they can just implement ApplicationContextAware to get a context passed to them.

A simple example. In your Spring XML, to get it to scan your package for beans, put the following in your Spring xml.

  <context:component-scan base-package="ca.intelliware.foo" />

This would automatically pick up classes that look like this:

public LunchMenu {
Restaurants restaurants;

    public List<Soup> getSoups(String restaurantName) {
        return restaurants.getRestaurant(restaurantName).getSoups();

And now to use this Spring component, I just do the following.

public SoupPrinter implements ApplicationContextAware {
    ApplicationContext context;

    public void printSoups(String restaurantName) {
        LunchMenu lunchMenu = (LunchMenu)context.getBean(LunchMenu.class.getSimpleName());

I just typed that code now on i-proving so I’m sure there are typos, but you get the general idea. Put a <context:component-scan> in your Spring XML, tag your components with @Component, inject using @Autowired, and then look up your beans by name. Easy peasy. No messy XML that you have to hand-edit every time you refactor!

Further reading:

Annotation-Driven Dependency Injection in Spring 2.1
Customizing Annotation Configuration and Component Detection in Spring 2.1

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

1 thought on “Look Ma, no XML! How to use annotations to eliminate declarations in XML.

  1. Pingback: Autowiring prototypes | i-Proving

Leave a Reply