Spring Autowiring & Component Scanning Problems - Part 6: The Remedy

Part 5 can be found here

So what can you do about root context beans not being wired correctly?

One solution is to ensure that all your root context beans have their autowiring specified via XML, either with explicit elements or autowire="byType" or autowire="byName" XML attributes, but this is a bit of a backward step considering how annotation centric Spring is becoming.

You could enable component scanning (via the XML element) and go through the beans marking them with the @Component family of annotations so that the @Autowired statements are picked up. You will also need to remove the XML-based bean definitions from the context files otherwise you will end up with two conflicting beans - one loaded due to the XML declaration and another loaded due to component scanning.

Or you could switch on 'annotation awareness' by adding a XML element to your root application context files. In fact you only need to add it to one of the root context files as all the beans are loaded into the same context and looking for autowired annotations only happens once all the beans are loaded into the context.

Or you could do all of the above but then you might be creating new problems for yourself... ;-)

Spring Autowiring & Component Scanning Problems - Part 5: The Cause

Part 4 can be found here

It's not clearly stated in the Spring documentation but the auto-wiring stage for DispatcherServlets only scan through the beans within it's specific application context searching for autowiring annotations (@Autowired, @Qualifier, etc.), it does not venture into the root application context to wire those beans.

It sometimes appears that it does cross that root context boundary if you have root bean classes annotated with one of the @Component family and you enable your web application's component scanning to include that package. What happens is that the bean is loaded into the root application context and then an overwritten version is loaded into the WebApplicationContext. This overlaid version is then auto-wired as it lives inside the WebApplicationContext.

Part 6 can be found here