Spring 概念模型接口 ImportSelector : 配置类导入选择器

概述

Spring中,如果想基于一个给定的选择标准(selection criteria),比如一个或者多个注解属性导入一些配置类(使用@Configuration的那些类),某个bean注册器,可以实现接口ImportSelector来实现这样的逻辑。

一个ImportSelector实现类通常也可能会实现各种Aware接口,如果实现了这些Aware接口,这些接口方法的调用会发生在selectImports之前。

ImportSelector#selectImports的调用在ConfigurationClassParser#processImports中。

实现类举例:

  • AutoConfigurationImportSelector

    Springboot用于从所有jar包的META-INF/spring.factories文件中加载所有的自动配置类:keyorg.springframework.boot.autoconfigure.EnableAutoConfiguration的项。

  • SessionAutoConfiguration$SessionConfigurationImportSelector

    根据当前Web环境类型决定启用哪个Session配置类。

一个ImportSelector通常被@Import注解使用,如下所示 :

//...
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    //...
}

ImportSelector#selectImports 返回的树组的元素的类型可以是以下三种情况之一 :

  1. ImportSelector (也就是说,一个ImportSelector可以导入另外一个ImportSelector)
  2. ImportBeanDefinitionRegistrar
  3. 某个配置类

源代码解析

package org.springframework.context.annotation;

import org.springframework.core.type.AnnotationMetadata;


public interface ImportSelector {

	/**
	 * Select and return the names of which class(es) should be imported based on
	 * the AnnotationMetadata of the importing @Configuration class.
     * 
     * 这里importingClassMetadata是使用@Import注解导入该ImportSelector
     * 的配置类的注解元数据。实现类可以实现该方法,根据导入类的注解元数据
     * 也就是importingClassMetadata,当然也可以结合考虑当前环境中的其他信息,
     * 决定导入哪些配置类。
	 */
	String[] selectImports(AnnotationMetadata importingClassMetadata);

}

有关文章

Spring 概念模型接口 ImportBeanDefinitionRegistrar: Bean定义导入器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值