Springboot @Import 详解

SpringBoot 的 @Import 用于将指定的类实例注入之Spring IOC Container中。

今天抽空在仔细看了下Springboot 关于 @Import 的处理过程, 记下来以后看。

1. @Import

先看Spring对它的注释 (文档贴过来的), 总结下来作用就是和xml配置的 <import />标签作用一样,允许通过它引入 @Configuration 注解的类 (java config), 引入ImportSelector接口(这个比较重要, 因为要通过它去判定要引入哪些@Configuration) 和 ImportBeanDefinitionRegistrar 接口的实现, 也包括 @Component注解的普通类。

但是如果要引入另一个xml 文件形式配置的 bean, 则需要通过 @ImportResource 注解。

/**
 * Indicates one or more {@link Configuration @Configuration} classes to import.
 *
 * <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
 * Allows for importing {@code @Configuration} classes, {@link ImportSelector} and
 * {@link ImportBeanDefinitionRegistrar} implementations, as well as regular component
 * classes (as of 4.2; analogous to {@link AnnotationConfigApplicationContext#register}).
 *
 * <p>{@code @Bean} definitions declared in imported {@code @Configuration} classes should be
 * accessed by using {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
 * injection. Either the bean itself can be autowired, or the configuration class instance
 * declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly
 * navigation between {@code @Configuration} class methods.
 *
 * <p>May be declared at the class level or as a meta-annotation.
 *
 * <p>If XML or other non-{@code @Configuration} bean definition resources need to be
 * imported, use the {@link ImportResource @ImportResource} annotation instead.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.0
 * @see Configuration
 * @see ImportSelector
 * @see ImportResource
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

  /**
   * {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
   * or regular component classes to import.
   */
  Class<?>[] value();

}

2. ImportSelector

因为 @Import 的实现有很多时候需要借助 ImportSelector 接口, 所以我们再看下这个接口的描述, 总结下来就是需要通过这个接口的实现去决定要引入哪些 @Configuration。 它如果实现了以下四个Aware 接口, 那么spring保证会在调用它之前先调用Aware接口的方法。

至于为什么要保证调用Aware, 我个人觉得应该是你可以通过这些Aware去感知系统里边所有的环境变量, 从而决定你具体的选择逻辑。

/**
 * Interface to be implemented by types that determine which @{@link Configuration}
 * class(es) should be imported based on a given selection criteria, usually one or more
 * annotation attributes.
 *
 * <p>An {@link ImportSelector} may implement any of the following
 * {@link org.springframework.beans.factory.Aware Aware} interfaces, and their respective
 * methods will be called prior to {@link #selectImports}:
 * <ul>
 * <li>{@link org.springframework.context.EnvironmentAware EnvironmentAware}</li>
 * <li>{@link org.springframework.beans.factory.BeanFactoryAware BeanFactoryAware}</li>
 * <li>{@link org.springframework.beans.factory.BeanClassLoaderAware BeanClassLoaderAware}</li>
 * <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}</li>
 * </ul>
 *
 * <p>ImportSelectors are usually processed in the same way as regular {@code @Import}
 * annotations, however, it is also possible to defer selection of imports until all
 * {@code @Configuration} classes have been processed (see {@link DeferredImportSelector}
 * for details).
 *
 * @author Chris Beams
 * @since 3.1
 * @see DeferredImportSelector
 * @see Import
 * @see ImportBeanDefinitionRegistrar
 * @see Configuration
 */
public interface ImportSelector {

  /**
   * Select and return the names of which class(es) should be imported based on
   * the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
   */
  String[] selectImports(AnnotationMetadata importingClassMetadata);

}

3. Springboot 对@Import注解的处理过程

Springboot对注解的处理都发生在AbstractApplicationContext -> refresh() -> invokeBeanFactoryPostProcessors(beanFactory) -> ConfigurationClassPostProcessor -> postProcessBeanDefinitionRegistry()方法中。

(稍微说下也免得我自己忘了, springboot初始化的普通context(非web) 是AnnotationConfigApplicationContext, 在初始化的时候会初始化两个工具类, AnnotatedBeanDefinitionReader 和 ClassPathBeanDefinitionScanner 分别用来从 annotation driven 的配置和xml的配置中读取beanDefinition并向context注册, 那么在初始化 AnnotatedBeanDefinitionReader 的时候, 会向BeanFactory注册一个ConfigurationClassPostProcessor 用来处理所有的基于annotation的bean, 这个ConfigurationClassPostProcessor 是 BeanFactoryPostProcessor 的一个实现,springboot会保证在  invokeBeanFactoryPostProcessors(beanFactory) 方法中调用注册到它上边的所有的BeanFactoryPostProcessor)

如下代码显示是通过 ConfigurationClassParser 类来转换的

// Parse each @Configuration class
    ConfigurationClassParser parser = new ConfigurationClassParser(
        this.metadataReaderFactory, this.problemReporter, this.environment,
        this.resourceLoader, this.componentScanBeanNameGenerator, registry);

那么在 ConfigurationClassParser -> processConfigurationClass() -> doProcessConfigurationClass() 方法中我们找到了 (这里边的流程还是很清楚的, 分别按次序处理了@PropertySource, @ComponentScan, @Import, @ImportResource, 在处理这些注解的时候是通过递归处理来保证所有的都被处理了)

// Process any @Import annotations
    processImports(configClass, sourceClass, getImports(sourceClass), true);

那接下来就看它到底是怎么做的 . 流程依然清晰 :

  首先, 判断如果被import的是 ImportSelector.class 接口的实现, 那么初始化这个被Import的类, 然后调用它的selectImports方法去获得所需要的引入的configuration, 然后递归处理

  其次, 判断如果被import的是 ImportBeanDefinitionRegistrar 接口的实现, 那么初始化后将对当前对象的处理委托给这个ImportBeanDefinitionRegistrar (不是特别明白, 只是我的猜测)

  最后, 将import引入的类作为一个正常的类来处理 ( 调用最外层的doProcessConfigurationClass())

所以, 从这里我们知道, 如果你引入的是一个正常的component, 那么会作为@Compoent或者@Configuration来处理, 这样在BeanFactory里边可以通过getBean拿到, 但如果你是 ImportSelector 或者 ImportBeanDefinitionRegistrar 接口的实现, 那么spring并不会将他们注册到beanFactory中,而只是调用他们的方法。

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
      Collection<SourceClass> importCandidates, boolean checkForCircularImports) {

    if (importCandidates.isEmpty()) {
      return;
    }

    if (checkForCircularImports && isChainedImportOnStack(configClass)) {
      this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
    }
    else {
      this.importStack.push(configClass);
      try {
        for (SourceClass candidate : importCandidates) {
          if (candidate.isAssignable(ImportSelector.class)) {
            // Candidate class is an ImportSelector -> delegate to it to determine imports
            Class<?> candidateClass = candidate.loadClass();
            ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
            ParserStrategyUtils.invokeAwareMethods(
                selector, this.environment, this.resourceLoader, this.registry);
            if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {
              this.deferredImportSelectors.add(
                  new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));
            }
            else {
              String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
              Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
              processImports(configClass, currentSourceClass, importSourceClasses, false);
            }
          }
          else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
            // Candidate class is an ImportBeanDefinitionRegistrar ->
            // delegate to it to register additional bean definitions
            Class<?> candidateClass = candidate.loadClass();
            ImportBeanDefinitionRegistrar registrar =
                BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
            ParserStrategyUtils.invokeAwareMethods(
                registrar, this.environment, this.resourceLoader, this.registry);
            configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
          }
          else {
            // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
            // process it as an @Configuration class
            this.importStack.registerImport(
                currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
            processConfigurationClass(candidate.asConfigClass(configClass));
          }
        }
      }
      catch (BeanDefinitionStoreException ex) {
        throw ex;
      }
      catch (Throwable ex) {
        throw new BeanDefinitionStoreException(
            "Failed to process import candidates for configuration class [" +
            configClass.getMetadata().getClassName() + "]", ex);
      }
      finally {
        this.importStack.pop();
      }
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解SpringBoot开发使用@ImportResource注解影响拦截器

    问题描述 今天在给SpringBoot项目配置拦截器的时候发现怎么都进不到拦截器的方法里面,在搜索引擎上看了无数篇关于配置拦截器的文章都没有找到解决方案. 就在我准备放弃的时候,在 CSDN 上发现了一篇文章,说的是SpringBoot 用了@ImportResource 配置的拦截器就不起作用了.于是我就赶紧到Application启动类看了一眼,果然项目中使用了@ImportResource 注解用于配置系统的参数. 代码如下: 启动类配置 package com.xx.xxx; impor

  • Spring注解@Resource和@Autowired区别对比详解

    前言 @Resource和@Autowired都是做bean的注入时使用,其实@Resource并不是Spring的注解,它的包是javax.annotation.Resource,需要导入,但是Spring支持该注解的注入. 1.共同点 两者都可以写在字段和setter方法上.两者如果都写在字段上,那么就不需要再写setter方法. 2.不同点 (1)@Autowired @Autowired为Spring提供的注解,需要导入包org.springframework.beans.factory

  • Spring条件注解@Conditional示例详解

    前言 @Conditional是Spring4新提供的注解,它的作用是根据某个条件创建特定的Bean,通过实现Condition接口,并重写matches接口来构造判断条件.总的来说,就是根据特定条件来控制Bean的创建行为,这样我们可以利用这个特性进行一些自动的配置. 本文将分为三大部分,@Conditional源码的介绍.Condition的使用示例和@Conditional的扩展注解的介绍. 一.@Conditional的源码 @Target({ElementType.TYPE, Elem

  • Spring中@Import的各种用法以及ImportAware接口详解

    @Import 注解 @Import注解提供了和XML中<import/>元素等价的功能,实现导入的一个或多个配置类.@Import即可以在类上使用,也可以作为元注解使用. @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Import { /** * {@link Configuration}, {@link ImportSelector}, {@link I

  • 浅谈Spring自定义注解从入门到精通

    在业务开发过程中我们会遇到形形色色的注解,但是框架自有的注解并不是总能满足复杂的业务需求,我们可以自定义注解来满足我们的需求.根据注解使用的位置,文章将分成字段注解.方法.类注解来介绍自定义注解 字段注解 字段注解一般是用于校验字段是否满足要求,hibernate-validate依赖就提供了很多校验注解 ,如@NotNull.@Range等,但是这些注解并不是能够满足所有业务场景的.比如我们希望传入的参数在指定的String集合中,那么已有的注解就不能满足需求了,需要自己实现. 自定义注解 定

  • spring注解@Import用法详解

    [1]@Import 参数value接收一个Class数组,将你传入的类以全类名作为id加入IOC容器中 ​比较简单,此处不做详细解释 [2]ImportSelector ImportSelector强调的是复用性,使用它需要创建一个类实现ImportSelector接口,实现方法的返回值是字符串数组,也就是需要注入容器中的组件的全类名.id同样也是全类名. ​ 上代码: //自定义逻辑返回需要导入的组件 public class MyImportSelector implements Impo

  • SpringBoot使用AOP+注解实现简单的权限验证的方法

    SpringAOP的介绍:传送门 demo介绍 主要通过自定义注解,使用SpringAOP的环绕通知拦截请求,判断该方法是否有自定义注解,然后判断该用户是否有该权限.这里做的比较简单,只有两个权限:一个普通用户.一个管理员. 项目搭建 这里是基于SpringBoot的,对于SpringBoot项目的搭建就不说了.在项目中添加AOP的依赖:<!--more---> <!--AOP包--> <dependency> <groupId>org.springfram

  • Springboot @Import 详解

    SpringBoot 的 @Import 用于将指定的类实例注入之Spring IOC Container中. 今天抽空在仔细看了下Springboot 关于 @Import 的处理过程, 记下来以后看. 1. @Import 先看Spring对它的注释 (文档贴过来的), 总结下来作用就是和xml配置的 <import />标签作用一样,允许通过它引入 @Configuration 注解的类 (java config), 引入ImportSelector接口(这个比较重要, 因为要通过它去判

  • springboot定时任务详解

    在我们开发项目过程中,经常需要定时任务来帮助我们来做一些内容, Spring Boot 默认已经帮我们实行了,只需要添加相应的注解就可以实现 一.基于注解(静态) 1.pom 包配置 pom 包里面只需要引入 Spring Boot Starter 包即可 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactI

  • SpringBoot Aop 详解和多种使用场景解析

    前言 aop面向切面编程,是编程中一个很重要的思想本篇文章主要介绍的是SpringBoot切面Aop的使用和案例 什么是aop AOP(Aspect OrientedProgramming):面向切面编程,面向切面编程(也叫面向方面编程),是目前软件开发中的一个热点,也是Spring框架中的一个重要内容.利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率. 使用场景 利用AOP可以对我们边缘业务进行隔离,降低无关业务逻辑耦

  • SpringBoot Web详解静态资源规则与定制化处理

    目录 1.相关概念 2.静态资源目录 3.静态资源访问前缀 4.欢迎页支持 5.自定义favicon 6.源码分析 1.相关概念 Spring Boot 默认为我们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各种属性. 建议使用Spring Boot的默认配置方式,如果需要特殊处理的再通过配置文件进行修改. 如果想要自己完全控制WebMVC,就需要在@Configuration注解的配置类上增加@EnableWebMvc, 增加该注解以后WebMvcAuto

  • SpringBoot图文并茂详解如何引入mybatis与连接Mysql数据库

    目录 创建一个SpringBoot项目 创建mysql表 编写实体类 配置Mapper 感叹 创建一个SpringBoot项目 其他不赘叙了,引入MyBaties.MySql依赖 创建mysql表 CREATE TABLE sp_users( `id` INT PRIMARY KEY, `username` VARCHAR(30), `age` INT ); 刚开始一直出现这个错误,弄的我怀疑人生,结果是最后一行不能加',' ,物是人非. INSERT INTO sp_users(id,`use

  • Maven管理SpringBoot Profile详解

    1. Spring Profile Spring可使用Profile绝对程序在不同环境下执行情况,包含配置.加载Bean.依赖等. Spring的Profile一般项目包含:dev(开发), test(单元测试), qa(集成测试), prod(生产环境).由spring.profiles.active属性绝定启用的profile. SpringBoot的配置文件默认为 application.properties(或yaml,此外仅心properties配置为说明).不同Profile下的配置

  • Java Apollo环境搭建以及集成SpringBoot案例详解

    环境搭建 下载Quick Start安装包 从Github下载:checkout或下载apollo-build-scripts项目 手动打包Quick Start安装包 修改apollo-configservice, apollo-adminservice和apollo-portal的pom.xml,注释掉spring-boot-maven-plugin和maven-assembly-plugin 在根目录下执行mvn clean package -pl apollo-assembly -am

  • 可能是史上最细的python中import详解

    以前在使用import的时候经常会因为模块的导入而出现一些问题,以及一些似懂非懂半疑惑半糊涂的问题,索性花了点时间研究了一些python引用的方法,并且动手操作试验了一下,深有感触,特留此文以作总结,如有不当之处欢迎评论指正 本文会尽我所能详细描述,字数会比较多,希望各位耐心看完. 首先我觉得应该先了解一下python的引用是怎么引用的 我们首先新建一个python文件demo.py print(dir()) dir()命令是获取到一个object的所有属性,当传值为空时默认传入的是当前py文件

  • SpringBoot开发详解之Controller接收参数及参数校验

    目录 Controller 中注解使用 传输参数的几种Method 获取参数的几种常用注解 使用对象直接获取参数 使用@Valid对参数进行校验 总结 Controller 中注解使用 接受参数的几种传输方式以及几种注解: 在上一篇中,我们使用了JDBC链接数据库,完成了简单的后端开发.但正如我在上文中抛出的问题,我们能不能更好的优化我们在Controller中接受参数的方式呢?这一篇中我们就来聊一聊怎么更有效的接收Json参数. 传输参数的几种Method 在定义一个Rest接口时,我们通常会

  • eclipse如何搭建Springboot项目详解

    一.分步骤集成 1.1 整合连接池hikariCP 介绍:HikariCP 是一个高性能的 JDBC 连接池组件,可以避免连接频繁建立.关闭的开销,实现数据库连接复用: 导入方式:创建spring boot项目,集成如截图 配置application.properties文件 spring.datasource.url=jdbc:mysql://ip地址/你的数据库名?serverTimezone=GMT%2B8 spring.datasource.username=root spring.da

随机推荐