As per Spring Doc-
Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML\'s
Solution to Question 1:
Yes, You can use @Componentscan
in as many configuraion classes. That is all up to you. It just registers the various annotated classes of some specific packages as beans. So if you have all the annotated classes component scanned by just using one @Componentscan
, that is enough, as all the required beans you wanted has been activated and registered in the DispatcherServlet container.
Solution to Question 2:
@Configuration
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyConfiguration extends WebMvcConfigurerAdapter {
...
}
Your question: Why here scanning for configuration class itself?
This @ComponentScan(basePackageClasses = { MyConfiguration.class })
is mentioning MyConfiguration.class as example. The question is what does this mean?
There are two ways to componentscan packages either by basepackage
attribute or basepackageclasses
. These two are same but using basepackageclasses
has two benefits which are:
It is both type-safe and adds IDE support for future refactoring
That simply means, in future, you may rename (via refactor) some of the base backages, and since you have renamed the base packages, you do not need to change @ComponentScan in your configuration classes if you have used basepackageclasses
attribute.
Now coming back to your 2nd question. Why MyConfiguration.class is specified as the value of basepackageclasses
attribute of @Componentscan
?
First of all, let us know this:
basepackageclasses
attribute takes string value which represents some marker class. That Marker class tells: Hey! register all the classes which are present in the package in which this class is present, including this class
So, here in your answer, all those classes will be component-scanned which are present in the package in which MyConfiguration.class is present.
Hence, Myconfiguration.class acts as the Configuration class as well as the marker class to component scan other classes as well. Which also implies all the annotated classes will get registered which are present in the package in which MyConfiguration.class is present, including MyConfiguration.class as it is annotated with @Configuration annotationbasepackageclasses
attribute can have other classes as well, like com.abc.org.Marker.class
Benefit:
So, if you rename packages, there is no problem, as you have marker classes, which help spring find the packages. These marker classes may or may not have any content inside, as it just acts as a marker to find packages.