Spring Autowiring & Component Scanning Problems - Part 1: The Problem

Let's set the scene a little: You're a developer on a long-running Spring-based web application. It's a reasonably large application developed before annotations were a twinkle in Spring's eye and so uses XML to declare the beans and wiring. Over time the use of annotations has grown - particularly in the area of annotated controllers - and you've started to add @Autowired annotations rather than explicitly defining the wiring in the XML application context files.

So now you've got a good mix of XML-defined beans and annotated ones, sometimes mixing the two together; a bean is declared in the XML context file but it's wirings are defined using @Autowired statements rather than the usual XML elements.

Everything is working perfectly...

You've never had a problem adding @Autowired annotations to beans until now, but a particular bean's members don't seem to get wired (you get a NullPointerException at runtime) but you don't get a wiring error. This is confusing as you know that the @Autowired annotation has 'required' set to true by default, so it should be throwing a wiring exception during the loading of the context at the very least!

Why is it not wiring correctly? Because Spring is not even seeing the @Autowired annotation! To fully understand the issues at hand we need to wind back a bit and cover some theory.

Part 2 can be found here

No comments: