javaspringspring-mvccomponent-scan

@ComponentScan with multiple configuration class : Annotation Based Configuration


As per Spring Doc-

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.

In my spring web application there are multiple files those are marked @Configuration,in order to register @component bean in spring container-

Question1- Can we use @ComponentScan in any of the @Configuration class or in all @Configuration classes?

Question2-

Also I seen in spring doc

@Configuration
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyConfiguration extends WebMvcConfigurerAdapter {
...
}

Why here scanning for configuration class itself.

edit: Basically my understanding with @ComponentScan is to scan and register stereo type bean(ex- @componant,@Controller,@Services etc..),why we are registering @Configuration Bean.


Solution

  • For your Question 1 -

    yes, you can register a bean using @ComponentScan in any of the configuration bean which is registered in spring container.you can register a bean into container by any of the following way-

    1. Use @Configuration to register bean in rootcontext or dispatchersevletcontext.
    2. Import a class in any @Configuration bean (which is already registered in container).

    Let say- you have MvcConfig class in which you are scanning component-

    @ComponentScan(basePackages = {"xxxx","yyyy","zzzz"})
    @Configuration
    public class MvcConfig  {
    ....
    }
    

    To register MvcConfig in container you must do-

    Either

    new AnnotationConfigWebApplicationContext().register(MvcConfig.class);
    

    Or

    new AnnotationConfigWebApplicationContext().register(AnotherConfig.class);
    
    @Configuration
    @Import({MvcConfig.class})
    public class AnotherConfig  {
    ....
    }
    

    For your Question 2 -

    Here spring is not only registering MyConfiguration.class but also all the component classes those are present in the package in which MyConfiguration defined.