Skip to main content

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... ;-)