Spring Framework FAQ: Top Questions
16. What is the difference between @ComponentScan and @Import in Spring?
@ComponentScan
and @Import
are both used for including additional configurations or components, but they operate differently.
📘 Comparison:
@ComponentScan
: Automatically detects and registers classes annotated with stereotypes like@Component
,@Service
, etc.@Import
: Manually includes one or more@Configuration
classes.
📥 Example:
@ComponentScan(basePackages = "com.example.services")
@Import(AppSecurityConfig.class)
@Configuration
public class AppConfig {
}
🏆 Expected Output:
Beans in 'com.example.services' are scanned; AppSecurityConfig beans are also loaded.
🛠️ Use Cases:
- Use
@ComponentScan
for automatic discovery. - Use
@Import
to explicitly include config classes.