@ComponentScan tells Spring where to look for classes marked with stereotype annotations such as @Component. When Spring creates the context, it creates instances of the discovered components and adds them as beans. section 2.2
Scanning and marking a class do different jobs: @Component identifies a class to add, while @ComponentScan specifies where to find it. In this configuration, marking a class alone is not enough; scanning must also be configured. section 2.2
Scan for a Parrot component
Mark Parrot with @Component, then put @ComponentScan(basePackages = "com.example.beans") on a @Configuration class. If Parrot is in that package, creating a context from the configuration lets you retrieve the Parrot bean by type. section 2.2
Listing 2.15 Using the @ComponentScan annotation to tell Spring where to look
@Configuration
@ComponentScan(basePackages = "com.example.beans") #A
public class ProjectConfig {
}See the configuration class that directs Spring to the component package. section 2.2
You can list multiple packages in basePackages. For example, an application can scan separate packages for services, repositories, and notification proxies. A model package without stereotype-annotated classes need not be listed in that configuration. section 4.2.1
Listing 4.11 Using @ComponentScan in the configuration class
@Configuration #A
@ComponentScan(
basePackages = {
"com.example.proxies",
"com.example.repositories",
"com.example.services"}
)
public class ProjectConfiguration {
}
See a configuration that scans three packages. section 4.2.1
Component scanning avoids a separate bean-creation method for each marked class. An @Bean method is an alternative when you want to create and configure an instance yourself; the two approaches can also be used together. section 2.2
