@ComponentScan 是一个Spring框架的注解,它的主要目的是为了让Spring框架能够找到自定义的组件,比如@Component和@Service等注解的类,并将它们注册为Spring应用上下文中的beans。
@ComponentScan注解通常在配置类上使用,它会扫描指定的包及其子包下的所有类,查找标记了注解的类,并注册为bean。
以下是一些使用 @ComponentScan的方法:
基本使用方法:
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
在这个例子中,Spring将扫描"com.example"包及其子包。
使用basePackageClasses属性:
@Configuration
@ComponentScan(basePackageClasses = MyRepository.class)
public class AppConfig {
}
在这个例子中,Spring将扫描MyRepository类所在的包以及其子包。
使用filter属性:
@Configuration
@ComponentScan(basePackages = "com.example",
includeFilters = @Filter(type = FilterType.ANNOTATION, classes = CustomAnnotation.class),
excludeFilters = @Filter(type = FilterType.CUSTOM, classes = CustomExcludeFilter.class))
public class AppConfig {
}
在这个例子中,Spring将扫描"com.example"包及其子包中标记了CustomAnnotation的类,但会排除被CustomExcludeFilter判定为true的类。
使用useDefaultFilters属性:
@Configuration
@ComponentScan(basePackages = "com.example", useDefaultFilters = false)
public class AppConfig {
}
在这个例子中,Spring将只会扫描"com.example"包下标记了@Component注解的类,不会扫描其子包。
以上就是@ComponentScan的一些基本使用方法,在实际开发中可以根据需要选择合适的方法使用。