本文主要是介绍Spring 的类扫描器分析 - ClassPathBeanDefinitionScanner,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简介
ClassPathBeanDefinitionScanner继承自ClassPathScanningCandidateComponentProvider,构造时要求指定一个BeanDefinitionRegistry对象,ClassPathBeanDefinitionScanner作用就是将指定包下的类通过一定规则过滤后 将Class 信息包装成 BeanDefinition 的形式注册到IOC容器中,有两个核心的方法:
1、scan方法
public int scan(String... basePackages) {int beanCountAtScanStart = this.registry.getBeanDefinitionCount();doScan(basePackages);// Register annotation config processors, if necessary.if (this.includeAnnotationConfig) {AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);}return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}
2、doScan方法:
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {Assert.notEmpty(basePackages, "At least one base package must be specified");Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();for (String basePackage : basePackages) {Set<BeanDefinition> candidates = findCandidateComponents(basePackage);for (BeanDefinition candidate : candidates) {ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);candidate.setScope(scopeMetadata.getScopeName());String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);if (candidate instanceof AbstractBeanDefinition) {postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);}if (candidate instanceof AnnotatedBeanDefinition) {AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);}if (checkCandidate(beanName, candidate)) {BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);definitionHolder =AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);beanDefinitions.add(definitionHolder);registerBeanDefinition(definitionHolder, this.registry);}}}return beanDefinitions;
}
自定义扫描器
通过自定义的扫描器,扫描指定包下所有被@MyBeanScanner 注释的类
定义一个注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyBeanScanner {
}
编写扫描器
class MyClassPathDefinitonScanner extends ClassPathBeanDefinitionScanner {
private Class type;
public MyClassPathDefinitonScanner(BeanDefinitionRegistry registry, Class<? extends Annotation> type){super(registry,false);this.type = type;
}
public void registerTypeFilter(){addIncludeFilter(new AnnotationTypeFilter(type));
}public void doScan(String basePackage){Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackage);beanDefinitionHolders.forEach((item)->{System.out.println(item.getBeanDefinition().getBeanClassName());});
}
}
测试自定义扫描器
public static void main(String[] args) {AnnotationConfigApplicationContext ac = newAnnotationConfigApplicationContext(AppConfig.class);MyClassPathDefinitonScanner myClassPathDefinitonScanner = new MyClassPathDefinitonScanner(ac, MyBeanScanner.class);myClassPathDefinitonScanner.registerTypeFilter();myClassPathDefinitonScanner.doScan("com.mi.asop.demo.bean");}
Mybatis 的Mapper注册器-ClassPathMapperScanner
Mybatis中的ClassPathMapperScanner继承了ClassPathBeanDefinitionScanner,先调用父类ClassPathBeanDefinitionScanner.doScan方法扫描包路径并注册bd(BeanDefinition对象),再调用processBeanDefinitions处理注册后的bd(BeanDefinition对象),下面是我自己定义的MyMapperClassPathScanner和Mybatis中的基本是一样的:
关于Mybatis的这块内容可参考https://mp.csdn.net/mdeditor/103304489#这篇博客,这里主要模拟mybatis中的ClassPathMapperScanner来完成mapper接口的动态代理对象的扫描和注册,上一篇博客没有利用ClassPathMapperScanner,是手动根据包名遍历解析的。
MyMapperClassPathScanner
public class MyMapperClassPathScanner extends ClassPathBeanDefinitionScanner {
private MyMapperFactoryBean myMapperFactoryBean = new MyMapperFactoryBean();
public MyMapperClassPathScanner(BeanDefinitionRegistry registry) {super(registry);
}
/*** 调用父类的doScan方法* @param basePackages* @return*/
public Set<BeanDefinitionHolder> doScan(String... basePackages) {/*** 调用父类doScan方法拿到扫描到的BeanDefinition*/Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);if (beanDefinitions.isEmpty()) {System.out.println("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");} else {this.processBeanDefinitions(beanDefinitions);}return beanDefinitions;
}
/*** 遍历beanDefinitions,动态改变beanClass和给构造方法传值* @param beanDefinitions*/
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions){Iterator var3 = beanDefinitions.iterator();while(var3.hasNext()) {BeanDefinitionHolder holder = (BeanDefinitionHolder) var3.next();GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();System.out.println("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface");definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());definition.setBeanClass(this.myMapperFactoryBean.getClass());}
}public void registerTypeFilter(){this.addIncludeFilter(new TypeFilter() {public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {return true;}});
}protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
}
}
MyImportBeanDefinitionRegister类(同上一篇博客)
第一种注册bd的注释了,主要看第二种,在最下面
public class MyImportBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
/*
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(MyScan.class.getName());String[] basePackages = ( String[])annotationAttributes.get("value");//拿到注解上的扫描的包的名称 com.mi.asop.demo.mapperString packageName = basePackages[0];//得到包下面所有的类String packagePath = "";String[] names = packageName.split("\\.");for(String name:names){packagePath+=name+"/";}String classPath = this.getClass().getResource("/").getPath()+packagePath;File file = new File(classPath);String[] list = file.list();for(String fileName:list){//com.mi.asop.demo.mapper.userMapperfileName = fileName.substring(0,fileName.lastIndexOf("."));String first = fileName.substring(0, 1);String after = fileName.substring(1);first = first.toLowerCase();String beanName = first+after;BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MyMapperFactoryBean.class);AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(packageName+"."+fileName);beanDefinitionRegistry.registerBeanDefinition(beanName,beanDefinition);}
}
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {Map<String, Object> annotationAttributes = annotationMetadata.getAnnotationAttributes(MyScan.class.getName());String[] basePackages = ( String[])annotationAttributes.get("value");MyMapperClassPathScanner myMapperClassPathScanner = new MyMapperClassPathScanner(beanDefinitionRegistry);myMapperClassPathScanner.registerTypeFilter();myMapperClassPathScanner.doScan(basePackages[0]);}
}
这篇关于Spring 的类扫描器分析 - ClassPathBeanDefinitionScanner的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!