Mitch Pronschinske is a Senior Content Analyst at DZone. That means he writes and searches for the finest developer content in the land so that you don't have to. He often eats peanut butter and bananas, likes to make his own ringtones, enjoys card and board games, and is married to an underwear model. Mitch is a DZone Zone Leader and has posted 2576 posts at DZone. You can read more from them at their website. View Full User Profile

Why You Should Use Spring's Annotations-Based Autowiring

04.05.2010
| 36430 views |
  • submit to reddit
Some people find value in having centralized, declarative configurations of XML files.  However, many of the things in those files are not configuration and they do not change after development.  Having a centralized configuration is usually only valuable in small projects.  Still, some people find comfort in knowing how the configuration is wired together as a whole, even though the same "wirings" are mainly just duplicated by the dependencies in the code.  Developers who use full autowiring with the @Autowired annotation for Spring have no problems leaving their external XML configs behind.

One of the most important reasons why someone would use autowiring (@Autowired) is to have one less abstraction in your system.  Even though it might be a simple layer, thats one less layer of complexity.  When it removes a full layer of abstract indirections, the bean name is essentially gone with the name still preserved because of XML.  At this point you can just wire the "Foo" interface directly into your bean and the run-time profile will choose an implementation.  

Now you can work with code while tracing implementations and dependencies.  When you encounter an autowired dependency in the code you just hit the "go to implementation" key in your IDE to bring up the list of known implementations.  Many times there will be just one implementation that takes you straight into the class.  With full autowiring, you'll know exactly which implementation is being used, which isn't always true for XML wiring.

                                     

In plenty of cases, XML configurations are full of inconsistencies and it's hard to tell which ones are intended and which ones are not.  Full autowiring works really well because it's built for a common pattern that most use cases follow.  You rarely need to use qualifiers in your configuration because there are other ways to solve these situations.  The only disadvantage is that you will need to change the way you code slightly to make it interact more smoothly with autowiring.  For example, a customer repository no longer implements the generic Repository<Customer> interface.  Instead, you can write an interface CustomerRepository that extends Repository<Customer>.  Also, you might need to tweak your coding for subclassing, but the side effect will be stronger typing.

Another gripe might be that you can only get this functionality with the Spring Framework and not in standard Java.  For that we'll have to wait and see if it gets included in a JSR, like JSR 250: Common Annotations.  Some don't know if this is a good approach in the long run, but SpringSource is using this approach in almost all of their systems.  It's not hard to change your systems to autowiring with annotations either.  It integrates very well with XML.  

Comments

Kesav Kumr Kolla replied on Tue, 2010/04/06 - 12:48am

Annotations are great reduces the XML configuration headaches etc.. The catch is parsing through annotations has added cost to it. I have developed a spring 3.0 application and hosted in GAE when annotations enabled and component scan being used the startup time is so large that GAE fails to even start the application. I had to switch from annotations to XML configurations to reduce the startup time.

Ronald Miura replied on Tue, 2010/04/06 - 6:08am in response to: Kesav Kumr Kolla

Weird... did you specify the package to 'component-scan'?

Nicolas Frankel replied on Tue, 2010/04/06 - 7:28am

Hi Mitchell,

I'm always happy to read your informative Daily Dose posts. That's why it sadens me to vigorously object to your article's conclusion.

Why do you use DI in the first place? If the answer is 'To decouple your code', then why use a proprietary Spring annotation that will bind you to Spring in the long run?

XML configuration may be (is) a bore, but with the right tool, namely Spring IDE, it is the best solution in terms of decoupling.

Using standard (javax.inject.*) is an option, @Autowired is not.

Lieven Doclo replied on Tue, 2010/04/06 - 9:18am

@Nicolas

I agree that the best decoupling is done through XML, but then again, how many project go down the Spring or EJB path and change their mind after a while? Bigger projects won't. 

While I use @Inject as much as I can, the new annotations of Spring 3.0 are too good not to be used and when you already made the choice to go with Spring, you might as wel go all the way. If you don't want to be coupled to any framework, your development options will be severely limited. You'll be completely standards-compliant, but at what cost?

I think the main point of this article is that when you're using Spring, you're better off using annotations (and some XML for the corner cases).

Jonathan Fisher replied on Tue, 2010/04/06 - 9:20am in response to: Nicolas Frankel

I agree with Nicolas... this is why we follow the XML route. I've had the opposite experience w/ @Autowired... it seems @Autowired works great for smaller projects, not the other way around. We decided to name our beans after the interface that fufill and include a default configuration. Then you simply select the spring xml with the implementation you want. We can have multiple configurations available that have slightly different underlying behavior. AFAIK, there isn't a way to convieniently to do this @Autowired. I'm going to go out on a limb and ask if you're doing all your spring wiring in one file? I think this is a bad pattern... Youre library projects should ask for dependencies, and your top level project should import the correct configuration files to fufill them. We've discovered that by having a proper cross-cutting of concerns and including a default spring configuration in library projects, your top level project is mainly import statements that satisfy dependencies. SpringIDE acts as a compiler of sorts to tell you if you're missing dependencies.

Peter Veentjer replied on Tue, 2010/04/06 - 10:12am in response to: Jonathan Fisher

Same here.

Autowiring an component scan is nice for small projects, but doesn't scale up to more complex logic. At my company we are currently removing a lot of componentscan/autowiring/gigaspace annotations and moving to a more centralized model (xml files). This make reuse of components a hell of a lot easier (we can wire up the same java objects in different ways for different environment) and it also make documentation a lot easier: you want to know what the system looks like and how dependency are configured? Look at the XML.

Some time ago I wrote a blog about it:

http://pveentjer.wordpress.com/2009/12/02/am-i-too-stupid-for-autowired/

PS:
XML certainly isn't a good language for the configuration, but it beats autowiring crap anyday.

 

Peter Veentjer

Multiverse: Software Transactional Memory for Java

http://multiverse.codehaus.org

Mitch Pronschinske replied on Tue, 2010/04/06 - 11:23am

Hello All,

Your comments have helped me (and surely some other readers) understand this issue more broadly, so thank you.  I'll take a look at your blog, Peter.  It seems like this is an important topic that requires further analysis.  I'd be happy to find more resouces on the subject of Autowiring vs. XML config, and more comments are welcome.  It would be interesting to see how the XML config discussion has evolved since autowiring.  

@Nicolas

Don't be saddened.  I welcome everyone's constructive criticism, and I thank you for it.  Glad you like the Dose.  :)

Craig Doremus replied on Tue, 2010/04/06 - 1:25pm

What about JSR-330? I'm new to DI Annotations, but can't JSR-330 annotations be used to gain 'standard support'? Spring's documentation (http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-annotation-config) seems to state that @Autwired and @Inject can be used interchangably.

Cristian Vasile... replied on Tue, 2010/04/06 - 2:23pm

Using JSR-330 annotations with Spring only gives you standard autowiring. And this has the same huge disadvantage that autowiring has: lack of decoupling and lack of control.

To have control, I need to have a third party that decides how to assemble my system. I don't want the system to decide how to assemble itself (by means of autowiring annotations).
Basically, what I'm missing is the concept of Guice Module (for an example see http://code.google.com/p/google-guice/wiki/LinkedBindings), which gives you a way to do controlled "autowiring".
In Guice, it's the module that decides how the system is assembled. Guice seems to me the only usable JSR 330 implementation.
Lacking that in Spring, and not wanting to lose control of my system, I will continue to use XML in Spring.

If you have only one implementation for an interface, in Guice, you don't even need to have explicit configuration in your module. It's autodiscovered (autowired? :) ). For things that will never have more that one implementation this might be acceptable, but it's a decision that you can make. It's not the frameworks that forces you to make that decision. You can even change your mind later when you add another implementation, and add the proper configuration.

By the way, in many cases, when you have multiple implementations, using qualifiers is conceptually wrong because (again), the decision to use an implementation or another comes from outside the system (production vs. development mode, RDBMS specific configuration etc.).

Craig Doremus replied on Tue, 2010/04/06 - 4:17pm in response to: Cristian Vasile Mocanu

Thanks for your reply.

I found this Spring 3 example on the web that seems to use the ApplicationConfig class in the example like a module in Guice: http://etechguide.in/spring/spring3_annotation_di/

Do I have that right or am I just blowing smoke?

 

Nicolas Frankel replied on Tue, 2010/04/06 - 5:21pm

He he, notice that in my previous comment, I didn't say anything about autowiring?

Older people (like me...) remember that autowring can be used with XML. Well, guess what, I think it's a big error too. And the error gets bigger with bigger projects: haven't experienced it yet like Jonathan and Peter but it smells wrong... It happens when you rely too much on magic behind the scene. Add one more class and kaboom goes your DI! Good luck to you if you are adding features on an already developed application.

@Lieven

I can't agree with you. Java and JEE, though flawed, have come to be one of the most successfull stack on the server-side. Before JPA, I used Hibernate. I still use it when JPA doesn't fit my needs. Yet, I try to always use standards, when they do not impair development time (like JDO and EJB 2 IMHO).

What if the Spring developers decided to remove @Autowired in the next version of Spring? I wouldn't be able to upgrade Spring's version. Experience have taught me that it never happened in the Java/JEE APIs and I try to build my applications to last. My current customer wants its applications to last 10 years at least: so standards never hurts (less the ones that do... see example above)

@Mitchell

This post and my comment triggered an heated argument among my co-workers and me. Good job and thank you... but I still disagree with the content :-P

 

 

John Mcginn replied on Wed, 2010/04/07 - 9:18am

Everytime someone uses autowiring on any project of substantial size, a developer cries.

 Honestly we have had nothing but problems when teams use, despite our recommendations, auto wiring. 

 XML configuration is:

1.  Very explicit, you can'get any more explicit without doing it directly in Java.

2.  Very readable and traceable even if I'm not using an IDE tool

3.  Central

4.  Very flexible, I can create and wire up beans any way I want, including different instances of the same class.

 Autowiring on the other hand is:

1.  Not explicit at all or requires you to use qualifiers 

2.  Not readable at all and not traceable unless you are using an IDE tool

3.  Spread every where.

4.  Adds an extra invisible layer of abstraction that hides what is really being done.

5.  Must be done very carefully to prevent the oh oh I need to add a second data source to my project and I have it autowired over 500 classes, that I now have to go and add qualifiers too.  BOOM.

6.  Is near impossible to have a class where you inject different dependencies to change its behavior.

John Mcginn replied on Wed, 2010/04/07 - 9:20am

"In plenty of cases, XML configurations are full of inconsistencies and it's hard to tell which ones are intended and which ones are not."

 

What does this statement mean?  What inconsistencies does XML config have? 

Emil Ong replied on Wed, 2010/04/07 - 12:11pm


Another gripe might be that you can only get this functionality with the Spring Framework and not in standard Java.

 

 Mitch, unless I missed something, Java CDI supports everything you mentioned in the article and more WRT annotation-based injection. It's certainly standard as part of Java EE 6 and at least Weld of the CDI implementations support running in the JDK.

 

You rarely need to use qualifiers in your configuration because there are other ways to solve these situations. The only disadvantage is that you will need to change the way you code slightly to make it interact more smoothly with autowiring. For example, a customer repository no longer implements the generic Repository<Customer> interface. Instead, you can write an interface CustomerRepository that extends Repository<Customer>. Also, you might need to tweak your coding for subclassing, but the side effect will be stronger typing.

 

You can use annotation qualifiers to avoid that problem. Of course CDI supports this and I'm pretty sure Spring does as well. I think a mix of annotation qualifiers and XML would be beneficial to many of the earlier commenters. An all or nothing approach of either has significant downsides. Using both techniques, you can choose the best place to apply both. For example, you might autowire services that really only compose in a single way to allow better code isolation practices, but anything you really intend to be configurable, leave to XML.

 Good discussion!

Siva Kumar Rama... replied on Mon, 2011/11/14 - 2:09am

Good morning to all, I am new to developing spring MVC framework. Can anyone please explain the step by step process of creating annotataion based auto wired. And how to develop application using auto wires.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.