<context:component-scan>

The context:component-scan tag does the same functions as context:annotation-config, plus it scans the packages and marks the stereotype-annotated classes as spring beans. Declaring each bean in the XML files would be unnecessary if the spring configuration file had the context:component-scan element.

Annotation Activation by <context:component-scan>

Essentially, package scanning is used by <context:component-scan> to identify the annotations. It instructs Spring about which packages to search in order to find the components or beans that have been annotated. <context:component-scan> may identify a number of them, including @Component, @Repository, @Service, @Controller, @RestController, and @Configuration.

XML




<context:component-scan base-package="org.w3wiki">
  
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/>
    <context:include-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
  
</context:component-scan>


Spring MVC context:annotation-config VS context:component-scan

In this article, we will learn about Spring MVC <context:annotation-config> vs <context:component-scan>. Activating all annotations existing in Java beans that have already been registered either by definition in an application context file or by component scanning is the primary function of annotation-config. The requirement for registration is crucial. The component scan assigns the Spring Bean registration to Java classes annotated with @component, @service, @repository, and other attributes. It can do all the functions that annotation config can.

Similar Reads

Annotations in beans previously registered in the application context can be activated using context:annotation-config, regardless of whether they were specified using XML or via package scanning. This implies that for beans that have already been produced and saved in the spring container, it will resolve the @Autowired and @Qualifier annotations....

...

Difference between and

The context:component-scan tag does the same functions as context:annotation-config, plus it scans the packages and marks the stereotype-annotated classes as spring beans. Declaring each bean in the XML files would be unnecessary if the spring configuration file had the context:component-scan element....

Conclusion

...