在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将扫描这些类所在的包及其子包。