How component scanning works in Spring?

Spring can automatically scan a package for beans if component scanning is enabled.
@ComponentScan configures which packages to scan for classes with annotation configuration.

@Configuration
@ComponentScan(basePackages = "org.techlearnings.security")
class SecurityConfig {
    // Implementation logic goes here
}

Also, we can point to classes in the base packages with the basePackageClasses argument:

@Configuration
@ComponentScan(basePackageClasses = SecurityConfig.class)
class SecurityConfig {
    // Implementation logic goes here
}

Both arguments are arrays so that we can provide multiple packages for each.
If no argument is specified, the scanning happens from the same package where the @ComponentScan annotated class is present.
@ComponentScan leverages the Java 8 repeating annotations feature, which means we can mark a class with annotation multiple times:

@Configuration
@ComponentScan(basePackages = "org.techlearnings.security")
@ComponentScan(basePackageClasses = SecurityConfig.class)
class SecurityConfig {
    // Implementation logic goes here
}

Alternatively, we can use @ComponentScans to specify multiple @ComponentScan configurations:

@Configuration
@ComponentScans({
    @ComponentScan(basePackages = "org.techlearnings.security")
    @ComponentScan(basePackageClasses = SecurityConfig.class)
})
class SecurityConfig {
    // Implementation logic goes here
}

When using XML configuration, the configuring component scanning is just as easy:

<context:component-scan base-package="org.techlearnings">

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.