在Spring中,我們可以使用@ComponentScan
注解來配置要掃描的包。@ComponentScan
注解可以放在配置類上,用來指定要掃描的包路徑。以下是一些常見的配置方式:
@Configuration
@ComponentScan(basePackages = "com.example.package")
public class AppConfig {
// 配置其他Bean
}
@Configuration
@ComponentScan(basePackages = {"com.example.package1", "com.example.package2"})
public class AppConfig {
// 配置其他Bean
}
@Configuration
@ComponentScan(basePackages = "com.example.package",
includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.example.package.*")})
public class AppConfig {
// 配置其他Bean
}
@Configuration
@ComponentScan(basePackages = "com.example.package",
includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyComponent.class)})
public class AppConfig {
// 配置其他Bean
}
@Configuration
@ComponentScan(basePackages = "com.example.package",
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class)})
public class AppConfig {
// 配置其他Bean
}
注意:默認情況下,@ComponentScan
會自動掃描與配置類相同的包及其子包。你還可以使用basePackageClasses
屬性,指定一個或多個類,Spring將掃描這些類所在的包及其子包。