Component Scanning

Basic Spring
≈ 2 min read

Do not register every class by hand

When there are dozens or hundreds of beans, listing each one in configuration is inconvenient. Component Scanning lets Spring walk through specified packages, find suitable classes, and automatically register them in the container.

@Configuration
@ComponentScan("com.example.app")
class AppConfig {
}

@Service
class OrderService {
}

When the context is created, Spring scans the com.example.app package and its subpackages. OrderService is found as a component and becomes a bean in the container.

Stereotype annotations

The basic annotation is @Component. @Service, @Repository, and @Controller are more semantic variants for different class roles. When reading code, that is a useful signal: the annotation immediately shows the component's purpose.

The scan boundary matters. If a package containing a component is outside the scan area, Spring will not register it, even if the class has the correct annotation.

Component Scanning works well for your own application classes. But sometimes you need to register an object from a third-party library or create a bean in a nonstandard way. Explicit Java configuration is more convenient for that — we will cover it next.