@ComponentScan过滤不需要的类
前言
因为maven工程互相依赖,但是不需要依赖子项目的某些切面和配置类,这时项目会配置@ComponentScan扫码子工程的包,由于启动的时候已经加载到了容器类里面,于是就用上了@ComponentScan的excludeFilters属性。一、excludeFilters属性需要传递@ComponentScan.Filter注解
类型 | 描述 |
---|---|
annotation | 过滤器扫描使用注解标注的那些类,并通过expression指定注解全类名 |
assignable | 过滤器扫描派生于expression属性指定的类,比如spring的xml方式 |
aspectj | 过滤器扫描与expression属性所指定的AspectJ表达式所匹配的那些类 |
custom | 使用自定义的org.springframework.core.type.TypeFliter实现类,并通过expression指定全类名 |
regex | 过滤器扫描类的名称与expression属性指定正则表达式所匹配的那些类 |
二、示例
指定排除类
代码如下(示例):
//在启动类上加注解 多个类 逗号分隔
@ComponentScan(excludeFilters =
{@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {ControllerAspect.class})})
指定排除注解
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = ComponentScanIgnore.class))
自定义@ComponentScanIgnore实现
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ComponentScanIgnore{
}
过滤器
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class))
自定义过滤器MyTypeFilter
public class MyTypeFilter implements TypeFilter{
/**
* 过滤当前类的信息,如果包含的则不需要扫描
* @param metadataReader 读取当前正在扫描的信息
* @param metadataReaderFactory 可以获取到其他任何类的信息
* @return boolean
*/
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
//获取当前类注解的信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//获取当前正在扫描的类信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//获取当前类资源(类的路径)
Resource resource = metadataReader.getResource();
String className = classMetadata.getClassName();
//包含这个包路径的则被拦截
if(className.startsWith("com.danrenying.service")){
log.info("匹配到符合的类名>"+className);
return false;
}
return true;
}
}
表达式
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "com.danrenying.service.*"))