To autowire or not to autowire

Jason Zhicheng Li has written a blog article about Spring configuration. It is called the 12 Best Practices for Spring configuration. Best practice #1 was “don’t use autowiring*. That got me thinking:

I feel very ambivalent about autowiring. Initially, I thought it sounded like a great idea because it reduced clutter, but then people like Jason convinced me that it was not. The more I think about it, the more usure I am.

So, what are we afraid of when it comes to autowiring? Documenation is one thing, definately. In my experience, I don’t use the configuration much for documentation anyway. And we are used to automagic stuff happening anyway, so autowiring won’t be too different. Nothing stops us from explicit wiring in the cases where autowire would be too “undocumented”.

So what can go wrong? Either something gets shouldn’t be, or something doesn’t gets set which should. Autowire ensures nonambiguity, so if something gets set its always what should’ve been set.

As I can understand the issue, using autowire to, say, let all DAOs use the same DataSource seems much easier to manage than explicit wiring: If a class has setDataSource, it has the standard datasource. What could be easier?

I cannot see any realistic way where the first scenario would actually happen. If you have a setter on a bean, having it called can hardly be a surprise to you! Why else would you have it! If it wasn’t needed, it will not cause any harm, and if it was, it would be the right one.

Nor is there any great risk in a property being unset. If a property is critical, we already know how to deal with it: Dependency check or implementing InitializingBean.

So: We all have this fear of autowiring, but I have yet to understand a rational reason not to use it. (And yet, I don’t use autowiring either)

Can someone please explain WHY autowiring is bad without just waving their hands around? What bad things can happen if you autowire? Has anyone experienced any pains after autowiring?

This article has been posted as a comment to Jason’s blog

About Johannes Brodwall

Johannes is Principal Software Engineer in SopraSteria. In his spare time he likes to coach teams and developers on better coding, collaboration, planning and product understanding.
This entry was posted in Links, Technology. Bookmark the permalink.