Spring Framework: Spring Component scanning with @ComponentScan

Any class that is annotated with @Component or its special purpose annotation (@Controller, @Service or @Repository) can be identified as a spring managed bean or component. The spring framework should have the capability of identifying those annotated spring managed beans and creates and register them in spring ApplicationContext.  The component scanning will do this for spring.

The spring framework has a feature called component scanning and it will scan for the @Component or its special purposes annotations(as mentioned above) within the specified class packages(class-paths) for identifying spring managed components. After that it will create and register those components in the Spring ApplicationContext for the use of other components in the application.


How the component scanning is configured?

There are two ways.

  • Annotation based Configuration
    @ComponentScan(basePackages = {“com.springbootdev.samples”})
  • XML based Configuration
    <context:component-scan base-package =“com.springbootdev.samples”/>

(use either XML based or Annotation based configuration on your preference)

In simply, these configurations tells the spring to scan the given package (in this case “com.springbootdev.samples”) and its sub packages for finding the bean classes (spring managed components) that are annotated with @Component, @Controller, @Repostory and @Service. Once the relevant classes are discovered, Spring will create the instances of such annotated bean classes and register themselves in the ApplicationContext when the Spring IOC container loads.


During the initialization of Spring’s ApplicationContext, Spring will discover those @Autowired, @Inject and @Resource annotations and inject the dependencies as required. 


The @ComponentScan tag tells Spring to scan the code for injectable beans annotated with @Component, @Controller, @Repository, and @Service as well as supporting the @Autowired, @Resource and @Inject annotations under the package (and all its sub-packages) specified.

One thought on “Spring Framework: Spring Component scanning with @ComponentScan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s