Skip to main content

Spring Autowiring & Component Scanning Problems - Part 2: Component Scanning

Part 1 can be found here

Instead of adding explicit beans to your XML files, Spring 2.5 introduced the @Component annotation family (@Service, @Controller, @Repository – all children of the @Component parent annotation). Simply add these object-level annotations to your class definitions to mark what type of Spring bean they are. Then add the following XML snippet to the application context XML file to tell Spring where to look:
<context:component-scan base-package="com.andrewbeacock"/>
Spring now scans through the whole classpath for the specified package (and sub-packages) looking for @Component-based classes. Any found are created as beans and placed in the application context.

This purely adds the beans to the relevant application context, it doesn't look inside the class for other annotations until it's finished loading all the remaining beans into the context.

Part 3 can be found here

Comments