同胞兄弟,ImportSelector接口与DeferredImportSelector接口的区别

本文主要是介绍同胞兄弟,ImportSelector接口与DeferredImportSelector接口的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、前言
  • 二、ImportSelector和DeferredImportSelector的区别
  • 三、分析spring源码中对这两个接口的处理
    • 3.1 ConfigurationClassParser类的方法parse()
    • 3.2 parse()方法调用processConfigurationClass()方法
    • 3.3 processConfigurationClass()方法调用doProcessConfigurationClass()方法
    • 3.4 源码解析:processImports()
    • 3.5 源码解析:processDeferredImportSelectors()
  • 四、面试金手指(ImportSelector和DeferredImportSelector的区别)
  • 五、小结

一、前言

上一篇博客【Spring源码解析 011 Spring处理Imports注解】知道,在使用@Import注解来注册bean的时候,Import注解的值可以是ImportSelector或者DeferredImportSelector的实现类spring容器会实例化这个实现类,并执行其selectImports方法

这篇博客的问题是:ImportSelector和DeferredImportSelector的区别在哪里,我们自定义Imort逻辑的时候该选择哪个呢?本文通过分析相关的spring源码来查找答案;

本文接口:

  1. ImportSelector和DeferredImportSelector的区别;
  2. 分析spring源码中对这两个接口的处理;

二、ImportSelector和DeferredImportSelector的区别

  1. DeferredImportSelector接口是ImportSelector接口的一个扩展;
  2. ImportSelector实例的selectImports方法的执行时机,是在@Configguration注解中的其他逻辑被处理之前,所谓的其他逻辑,包括对@ImportResource、@Bean这些注解的处理(注意,这里只是对@Bean修饰的方法的处理,并不是立即调用@Bean修饰的方法,这个区别很重要!);
  3. DeferredImportSelector实例的selectImports方法的执行时机,是在@Configguration注解中的其他逻辑被处理完毕之后,所谓的其他逻辑,包括对@ImportResource、@Bean这些注解的处理;
  4. DeferredImportSelector的实现类可以用Order注解,或者实现Ordered接口来对selectImports的执行顺序排序;

三、分析spring源码中对这两个接口的处理

3.1 ConfigurationClassParser类的方法parse()

public void parse(Set<BeanDefinitionHolder> configCandidates) {this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>();//检查每个bean的定义for (BeanDefinitionHolder holder : configCandidates) {BeanDefinition bd = holder.getBeanDefinition();try {if (bd instanceof AnnotatedBeanDefinition) {//对于每个有注解的类,都执行方法parse(AnnotationMetadata metadata, String beanName)parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());   // parse方法,两个参数}else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());   // parse方法,两个参数}else {parse(bd.getBeanClassName(), holder.getBeanName());   // parse方法,两个参数}}catch (BeanDefinitionStoreException ex) {throw ex;}catch (Exception ex) {throw new BeanDefinitionStoreException("Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);}}//最后再处理DeferredImportSelector的实现类   要进去看看processDeferredImportSelectors();}

由以上代码可以大致看出DeferredImportSelector的实现类被最后放在processDeferredImportSelectors方法中处理,那么前面的parse(AnnotationMetadata metadata, String beanName)做了些什么呢?继续看;

3.2 parse()方法调用processConfigurationClass()方法

展开方法parse(AnnotationMetadata metadata, String beanName)里面,是执行processConfigurationClass方法;

3.3 processConfigurationClass()方法调用doProcessConfigurationClass()方法

再展开processConfigurationClass方法,看到核心逻辑是调用doProcessConfigurationClass方法,展开看看:

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {//为了聚焦Import相关处理,此处略去部分不相关代码,不在这里展示了......// 处理@Import注解  1、 要进去里面看具体逻辑 processImports()processImports(configClass, sourceClass, getImports(sourceClass), true);// 处理@ImportResource注解if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);String[] resources = importResource.getStringArray("value");Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");for (String resource : resources) {String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);configClass.addImportedResource(resolvedResource, readerClass);}}// 处理@Bean注解,注意是处理注解,不是执行@Bean修饰的方法Set<MethodMetadata> beanMethods = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName());for (MethodMetadata methodMetadata : beanMethods) {configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));}// 处理Configuration类的父类,外面在调用doProcessConfigurationClass方法的时有迭代处理,确保所有父类的注解都会被处理if (sourceClass.getMetadata().hasSuperClass()) {String superclass = sourceClass.getMetadata().getSuperClassName();if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {this.knownSuperclasses.put(superclass, configClass);// Superclass found, return its annotation metadata and recursereturn sourceClass.getSuperClass();}}// 再也没有父类了,返回null表示当前Configuration处理完毕return null;}

根据doProcessConfigurationClass(),可以梳理出下图中的逻辑:

在这里插入图片描述

现在需要再看看processImports和processDeferredImportSelectors这两个方法的具体代码;

3.4 源码解析:processImports()

先看processImports方法:

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,Collection<SourceClass> importCandidates, boolean checkForCircularImports) throws IOException {if (importCandidates.isEmpty()) {return;}if (checkForCircularImports && this.importStack.contains(configClass)) {this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));}else {this.importStack.push(configClass);try {for (SourceClass candidate : importCandidates) {//如果是ImportSelector接口的实现类,就在此处理if (candidate.isAssignable(ImportSelector.class)) {// Candidate class is an ImportSelector -> delegate to it to determine importsClass<?> candidateClass = candidate.loadClass();//实例化这些ImportSelector的实现类ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);//如果这实现类还实现了BeanFactoryAware、EnvironmentAware这些接口,就要先执行这些接口中声明的方法invokeAwareMethods(selector);//如果这个实现类也实现了DeferredImportSelector接口,就被加入到集合deferredImportSelectors中if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {this.deferredImportSelectors.add(new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));}else {//注意,这一行是关键代码!!!执行实现类的selectImports方法String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);processImports(configClass, currentSourceClass, importSourceClasses, false);}}//此处略去的和ImportSelector不相关的逻辑代码.........}}catch (BeanDefinitionStoreException ex) {throw ex;}catch (Exception ex) {throw new BeanDefinitionStoreException("Failed to process import candidates for configuration class [" +configClass.getMetadata().getClassName() + "]", ex);}finally {this.importStack.pop();}}}

以上代码有两个关键点:(因为)
第一、当前被处理的类,如果实现了DeferredImportSelector接口,就被加入到集合deferredImportSelectors中,还没有处理;
第二、当前被处理的类,如果没有实现DeferredImportSelector接口,但是实现了ImportSelector接口,就立即处理,就被执行selectImports方法;

金手指1:因为DeferredImportSelector接口是ImportSelector接口的子接口,所有判断逻辑在ImportSelector接口的if判断的里面
(1)当前被处理的类,如果实现了DeferredImportSelector接口,就被加入到集合deferredImportSelectors中,还没有处理;
(2)当前被处理的类,如果没有实现DeferredImportSelector接口,但是实现了ImportSelector接口,就立即处理,就被执行selectImports方法;
金手指2:processImports()方法中执行selectImports()方法的位置,找到selectImports()方法执行的位置就好了。
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
ImportBeanDefinitionRegistrar的处理
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
普通类
在这里插入图片描述

3.5 源码解析:processDeferredImportSelectors()

接下来看看processDeferredImportSelectors方法的源码,提前推测应该是处理集合deferredImportSelectors中的所有类,这些类都实现了DeferredImportSelector接口:

private void processDeferredImportSelectors() {List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;this.deferredImportSelectors = null;//按照Order注解或者Ordered接口进行排序Collections.sort(deferredImports, DEFERRED_IMPORT_COMPARATOR);for (DeferredImportSelectorHolder deferredImport : deferredImports) {ConfigurationClass configClass = deferredImport.getConfigurationClass();try {//此处是关键代码,执行DeferredImportSelector实现类的selectImports方法String[] imports = deferredImport.getImportSelector().selectImports(configClass.getMetadata());processImports(configClass, asSourceClass(configClass), asSourceClasses(imports), false);}catch (BeanDefinitionStoreException ex) {throw ex;}catch (Exception ex) {throw new BeanDefinitionStoreException("Failed to process import candidates for configuration class [" +configClass.getMetadata().getClassName() + "]", ex);}}}

至此,源码分析完毕了,从代码可以很清晰的看出ImportSelector与DeferredImportSelector的区别,就是selectImports方法执行时机有差别,这个差别期间,spring容器对此Configguration类做了些其他的逻辑:包括对@ImportResource、@Bean这些注解的处理(注意,这里只是对@Bean修饰的方法的处理,并不是立即调用@Bean修饰的方法,这个区别很重要!);

四、面试金手指(ImportSelector和DeferredImportSelector的区别)

  1. DeferredImportSelector接口是ImportSelector接口的一个扩展;
  2. ImportSelector实例的selectImports方法的执行时机,是在@Configguration注解中的其他逻辑被处理之前,所谓的其他逻辑,包括对@ImportResource、@Bean这些注解的处理(注意,这里只是对@Bean修饰的方法的处理,并不是立即调用@Bean修饰的方法,这个区别很重要!);
  3. DeferredImportSelector实例的selectImports方法的执行时机,是在@Configguration注解中的其他逻辑被处理完毕之后,所谓的其他逻辑,包括对@ImportResource、@Bean这些注解的处理;
  4. DeferredImportSelector的实现类可以用Order注解,或者实现Ordered接口来对selectImports的执行顺序排序;

根据doProcessConfigurationClass(),可以梳理出下图中的逻辑:

在这里插入图片描述

ImportSelector与DeferredImportSelector的区别,就是selectImports方法执行时机有差别,这个差别期间,spring容器对此Configguration类做了些其他的逻辑:包括对@ImportResource、@Bean这些注解的处理(注意,这里只是对@Bean修饰的方法的处理,并不是立即调用@Bean修饰的方法,这个区别很重要!);

五、小结

ImportSelector接口与DeferredImportSelector接口的区别,好了。

天天打码,天天进步!!!

这篇关于同胞兄弟,ImportSelector接口与DeferredImportSelector接口的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/481284

相关文章

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

CSS Padding 和 Margin 区别全解析

《CSSPadding和Margin区别全解析》CSS中的padding和margin是两个非常基础且重要的属性,它们用于控制元素周围的空白区域,本文将详细介绍padding和... 目录css Padding 和 Margin 全解析1. Padding: 内边距2. Margin: 外边距3. Padd

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

分辨率三兄弟LPI、DPI 和 PPI有什么区别? 搞清分辨率的那些事儿

《分辨率三兄弟LPI、DPI和PPI有什么区别?搞清分辨率的那些事儿》分辨率这个东西,真的是让人又爱又恨,为了搞清楚它,我可是翻阅了不少资料,最后发现“小7的背包”的解释最让我茅塞顿开,于是,我... 在谈到分辨率时,我们经常会遇到三个相似的缩写:PPI、DPI 和 LPI。虽然它们看起来差不多,但实际应用

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

GORM中Model和Table的区别及使用

《GORM中Model和Table的区别及使用》Model和Table是两种与数据库表交互的核心方法,但它们的用途和行为存在著差异,本文主要介绍了GORM中Model和Table的区别及使用,具有一... 目录1. Model 的作用与特点1.1 核心用途1.2 行为特点1.3 示例China编程代码2. Tab

Nginx指令add_header和proxy_set_header的区别及说明

《Nginx指令add_header和proxy_set_header的区别及说明》:本文主要介绍Nginx指令add_header和proxy_set_header的区别及说明,具有很好的参考价... 目录Nginx指令add_header和proxy_set_header区别如何理解反向代理?proxy

Java中&和&&以及|和||的区别、应用场景和代码示例

《Java中&和&&以及|和||的区别、应用场景和代码示例》:本文主要介绍Java中的逻辑运算符&、&&、|和||的区别,包括它们在布尔和整数类型上的应用,文中通过代码介绍的非常详细,需要的朋友可... 目录前言1. & 和 &&代码示例2. | 和 ||代码示例3. 为什么要使用 & 和 | 而不是总是使

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程