【Spring源码解析】组件注册-@ComponentScan自定义TypeFilter指定过滤规则
前言
接上一篇 Spring源码解析之@ComponentScan注册bean
实现
- 自定义过滤器
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 {
@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 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 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
|
最后
本篇到此结束,欢迎大家关注公众号【当我遇上你】。