Monday, October 22, 2007

So you thought Spring's autowiring was a no-no?

Think again.

Yet another Spring 2.5 feature, the @Autowired annotation gives you back the control of autowiring, by-type mind. Back in Spring 2.0, autowiring was considered by many to be an anti-pattern due to the lack of control and overview of which beans would actually be injected at runtime. With annotation driven injection (meaning you've got in some Spring XML file), objects are only injected when you explicitly state so.

This allows you to reduce the amount of dependency mapping in your Spring XML config files and replace them with annotations in your Java files. If you've got multiple implementations that are possible autowiring candiates, you segment them by using the @Qualifier annotation.

Rather than riddle this blog post with snippets of Java and XML, I want you to get the Spring source (you can import it into Eclipse easily) and check out this test:


I've been playing around with these features lately and must say they are working nicely. Beware of how/whether you decide to use the instead of explicitly stating your beans in XML files. Yup, this means you can pretty much avoid XML completely in your Spring configuration.

It's a matter of taste really, but be consistent in the way you declare your components (either by XML or annotation). Make sure your whole team are aware of what is going on, as it can still feel quite auto-magical to the non-initiated.

If you're not interested in fiddling with the Spring source (which you should be - it does after all provide quite a few examples on how the Spring devs are eating their own dogfood), you can click some of the links below:

Mark Fisher blogged about these features a while back, and Rod Johnson recently posted an extensive article on TheServerSide about Spring 2.5. The tutorial gives a good introduction to the entire set of 2.5 features, including the annotation driven injection I've mentioned in this post and the Spring TestContext Framework I blogged about earlier.

I'll take this opportunity to remind any Oslo developers that we're doing a Spring course together with Interface21 in November, an excellent opportunity to jump on the Spring wagon and get a kick-start on lightweight system development and architecture.