liveBook · Manning

@ComponentScan annotation

As explained in Spring Start Here, Second Edition

A Spring annotation that configures package scanning for classes marked with component stereotype annotations.

@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

How Spring Start Here, Second Edition covers it

How deep it goes
Explains the marking and scanning steps, shows single- and multiple-package configuration, and demonstrates context lookup.
Examples
Uses a Parrot component and a comment service with repository and notification dependencies.
What it assumes
Introduces stereotype-based bean creation after demonstrating the Spring context and @Bean configuration approach.
What you can do after
Operate/configure Spring component scanning for one or multiple packages and retrieve a discovered bean from the context.
How it connects
Connects stereotype annotations and Spring beans with @Bean configuration and dependency injection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.