Spring框架的ImportSelector使用场景
说起ImportSelector接口,不得不说@Import注解,该注解的作用是给容器中导入一个或多个组件,看下注释
public @interface Import {
/**
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
*/
Class<?>[] value();
}
可以看到在它的注释上有三个链接,分别是@Configuration、ImportSelector和ImportBeanDefinitionRegistrar。也就是@Import注解可以导入这三种类型到容器中,当然也可以导入一个普通的类到容器中,
接着回过头来看下ImportSelector接口
public interface ImportSelector {
/**
* 根据导入的Configuration类的注解元数据选择哪一个类需要被导入,返回的数组就是需要被导入的类名
* Select and return the names of which class(es) should be imported based on
* the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
* @return the class names, or an empty array if none
*/
String[] selectImports(AnnotationMetadata importingClassMetadata);
@Nullable
default Predicate<String> getExclusionFilter() {
return null;
}
}
这个接口比较重要的方法selectImports上面有注释。比较经典的做法是接口方法返回一个配置类以加载外部类。而且它的名字叫ImportSelector,导入选择器,顾名思义就是可以选择,也就是根据环境啊,变量什么的决定导入哪个,但是我为什么不直接用@Import注解导入一个配置类呢,这样可以少了ImportSelector这一层。有人可能说这样没法根据环境判断,但是可以在配置类上添加@Profile或者@Primary注解啊。那现在只剩下需要导入多个配置类的情况,可以使用这个接口返回配置类数组,对外来说只有一个接口,另外就是selectImports方法的参数AnnotationMetadata可以获取导入的配置类的所有注解。
综合来讲这个接口卵用不大,就目前的理解是这样的。