在配置类上添加@CompentScan注解来进行包扫描
@ComponentScan(basePackages = {"com.dgr.annotation.component_scan"})
public class MainConfig {
}
1. 排除用法 excludeFilters(排除@Controller注解的,和TulingService的)
@ComponentScan(basePackages = {"com.dgr.annotation.component_scan"}, excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyService.class)})
public class MainConfig {
}
2. ②:包含用法 includeFilters ,注意,若使用包含的用法,需要把useDefaultFilters属性设置为false(true表示扫描全部的)
@ComponentScan(basePackages = {"com.dgr.annotation.component_scan"}, includeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.CUSTOM, value = MyTypeFilter.class)
}, useDefaultFilters = false)
public class MainConfig {
}
3. @ComponentScan.Filter type的类型
a)注解形式的FilterType.ANNOTATION
@Controller @Service @Repository @Compent
b)指定类型的 FilterType.ASSIGNABLE_TYPE
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {MyService.class})
c)aspectj类型的 FilterType.ASPECTJ(不常用)
d)正则表达式的 FilterType.REGEX(不常用)
e)自定义的 FilterType.CUSTOM
@ComponentScan.Filter(type = FilterType.CUSTOM, value = MyTypeFilter.class)
public class MyTypeFilter 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();
return classMetadata.getClassName().contains("dao");
}
}