The @ComponentScan
annotation in Spring Boot is used to automatically detect and register beans (components, services, repositories, etc.) from the specified package(s) into the Spring Application Context.
Why is @ComponentScan
Needed?
By default, Spring Boot scans for components only in the package where the main application class is located and its sub-packages.
If your components are in different packages, you need @ComponentScan
to explicitly specify the packages to scan.
1. Define Components in Different Packages
Package: com.example.service
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class MyService {
public String getMessage() {
return "Hello from MyService!";
}
}
2. Enable Component Scanning in @SpringBootApplication
Package: com.example.app
package com.example.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = "com.example.service") // Scanning external package
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
Here, we explicitly tell Spring Boot to scan com.example.service
for beans.
How @ComponentScan
Works
- By default,
@SpringBootApplication
implicitly includes@ComponentScan
with the package of the main class. - If your beans are in different packages, you must specify
@ComponentScan(basePackages = "...")
. - It scans and registers beans annotated with:
@Component
@Service
@Repository
@Controller
@RestController
Multiple Packages Example
If your components are in multiple packages, specify them like this:
@ComponentScan(basePackages = {"com.example.service", "com.example.repository"})
Using @ComponentScan
with @Configuration
You can also use @ComponentScan
in a configuration class:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.service")
public class AppConfig {
}
Here, Spring Boot will scan com.example.service
for components.
Key Takeaways
- Auto-scans components to avoid manual bean registration.
- Required if components are outside the default package structure.
- Works with multiple base packages.
- Implicitly included in
@SpringBootApplication
.