在配置类上写@CompentScan注解来进行包扫描.
@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"})
public class MainConfig {
}
①: 排除用法 excludeFilters(排除@Controller注解的,和XxService的)
@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"},excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = { XxService.class})
})
public class MainConfig {
}
②: 包含用法 includeFilters ,注意,若使用包含的用法, 需要把useDefaultFilters属性设置为 false(true表
示扫描全部的)
@Configuration
@ComponentScan(basePackages = {"com.test.testcompentscan"},includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
},useDefaultFilters = false)
public class MainConfig {
}
③ @ComponentScan.Filter type的类型
a) 注解形式的FilterType.ANNOTATION @Controller @Service @Repository @Compent
b) 指定类型的 FilterType.ASSIGNABLETYPE @ComponentScan.Filter(type = FilterType.ASSIGNABLETYPE,value = {TulingService.class})
c) aspectj类型的 FilterType.ASPECTJ(不常用)
d) 正则表达式的 FilterType.REGEX(不常用)
e) 自定义的 FilterType.CUSTOM
public enum FilterType {
//注解形式 比如@Controller @Service @Repository @Compent
ANNOTATION,
//指定的类型
ASSIGNABLE_TYPE,
//aspectJ形式的
ASPECTJ,
//正则表达式的
REGEX,
//自定义的
CUSTOM
}
③ ①FilterType.CUSTOM 自定义类型如何使用
public class TestFilterType implements TypeFilter {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//获取当前类的注解源信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//获取当前类的class的源信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//获取当前类的资源信息
Resource resource = metadataReader.getResource();
if(classMetadata.getClassName().contains("dao")) {
return true;
}
return false;
}
}
@ComponentScan(basePackages = {"com.tuling.testcompentscan"},includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,value = TestFilterType .class)
},useDefaultFilters = false)
public class MainConfig {
}