Skip to main content

Spring Autowiring & Component Scanning Problems - Part 3: Autowiring

Part 2 can be found here

Having a load of beans instantiated in an application context is one thing, having them wired together so that they know about each other is another. Wiring can be done either using XML or via the @Autowired annotation. The annotations on their own don't cause Spring to wire the beans, you need to turn on annotation support for Spring to find them:
<context:annotation-config/>
When added to an application context XML file it instructs Spring to look through all the loaded beans in the relevant application context for annotations like @Autowired, @Qualifier & @Required. In a reasonably mature Spring application you could have the beans being wired together in a number of ways:
  • Explicit <property> XML elements referencing other beans
  • The addition of autowire="byType" or autowire="byName" XML attributes
  • @Autowired annotations inside normal classes declared as beans in XML
  • @Autowired annotations inside @Component-based classes
Note: The <context:component-scan> element also implicitly defines the <context:annotation-config> autowiring element as well - after all if you are scanning for annotated @Component classes you want the embedded @Autowired annotations to be scanned for as well.

Part 4 can be found here

Comments