【Spring源码解析】组件注册-@ComponentScan自定义TypeFilter指定过滤规则

前言

接上一篇 Spring源码解析之@ComponentScan注册bean

实现

  1. 自定义过滤器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class CustomTypeFilter implements TypeFilter {

/**
*
* @param metadataReader 读取到当前正在扫描的类的信息
* @param metadataReaderFactory 可以获取到其他任何类信息的
*/
@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();
System.out.println("自定义filter:" + className);
if (className.contains("Service")) {
return true;
}
return false;
}
}
  1. 配置过滤器
1
2
3
4
5
6
7
8
9
10
11
@Configuration
@ComponentScan(value = "cn.idea360", includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM, value = {CustomTypeFilter.class})
}, useDefaultFilters = false)
public class BeanConfig {

@Bean
public Person person() {
return new Person("config", 18);
}
}
  1. 测试

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
自定义filter:cn.idea360.IocTest
自定义filter:cn.idea360.bean.Person
自定义filter:cn.idea360.config.CustomTypeFilter
自定义filter:cn.idea360.controller.BookController
自定义filter:cn.idea360.dao.BookDao
自定义filter:cn.idea360.service.BookService
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
beanConfig
bookService

最后

本篇到此结束,欢迎大家关注公众号【当我遇上你】。