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@Configurationclasses.
📥 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
@ComponentScanfor automatic discovery. - Use
@Importto explicitly include config classes.
