概述
在Spring
中,如果想基于一个给定的选择标准(selection criteria
),比如一个或者多个注解属性导入一些配置类(使用@Configuration
的那些类),某个bean
注册器,可以实现接口ImportSelector
来实现这样的逻辑。
一个ImportSelector
实现类通常也可能会实现各种Aware
接口,如果实现了这些Aware
接口,这些接口方法的调用会发生在selectImports
之前。
ImportSelector#selectImports
的调用在ConfigurationClassParser#processImports
中。
实现类举例:
AutoConfigurationImportSelector
Springboot
用于从所有jar
包的META-INF/spring.factories
文件中加载所有的自动配置类:key
为org.springframework.boot.autoconfigure.EnableAutoConfiguration
的项。SessionAutoConfiguration$SessionConfigurationImportSelector
根据当前
Web
环境类型决定启用哪个Session
配置类。
一个ImportSelector
通常被@Import
注解使用,如下所示 :
//...
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
//...
}
ImportSelector#selectImports
返回的树组的元素的类型可以是以下三种情况之一 :
ImportSelector
(也就是说,一个ImportSelector
可以导入另外一个ImportSelector
)ImportBeanDefinitionRegistrar
- 某个配置类
源代码解析
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);
}