博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring框架的ImportSelector到底可以干嘛
阅读量:4109 次
发布时间:2019-05-25

本文共 5888 字,大约阅读时间需要 19 分钟。

前言

最近一直在钻研Spring源码,感觉要把自己看吐了,但是看到奥妙的地方还是会拍手称快。这次就总结一下Spring中一个非常重要的注解@Import中的ImportSelector接口的作用以及它到底有啥作用。也会捎带一部分源码说一下DeferredImportSelector是干啥的,以及Spring解析这个和ImportSelector有什么区别。更多Spring内容进入。

ImportSelector

说到ImportSelector这个接口就不得不说这里面最重要的一个方法:selectImports()

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. * 选择并返回需要导入的类的名称,这些类基于AnnotationMetadata * 并且导入到@Configuration注解的类中的 * @return the class names, or an empty array if none * 返回所有的class name,如果没有,就返回空 */ String[] selectImports(AnnotationMetadata importingClassMetadata); /** * 返回排除的类,是一个类过滤器,但是这个方法被default注解了, * 可见Spring公司也知道,这个基本没啥人用 */ @Nullable default Predicate
getExclusionFilter() {
return null; }}

源码的注解里说了一大堆,就直接说这个方法能干啥吧。这个方法的返回值是一个字符串数组,只要在配置类被引用了,这里返回的字符串数组中的类名就会被Spring容器new出来,然后再把这些对象放到工厂当中去。所以这有啥用呢?我们还是用一个例子演示一下。

ImportSelector简单例子

首先我们先有一个实现了ImportSelector的类MyImportSelect,再构造一个业务类IndexDao,然后配置类用@Import引入,最后测试类Test。

/** * 由于我们使用的ImportSelector所以就不需要放到Spring容器当中了。 * 我们要用@Import这个注解引入进去。 */public class MyImportSelect implements ImportSelector {
@Override public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{
IndexDao.class.getName()}; }}
@ComponentScan("com.demo")@Import(MyImportSelect.class)public class AppConfig {
}
public class IndexDao {
public void query(){
System.out.println("query IndexDao for MyImportSelect"); }}
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext anno=new AnnotationConfigApplicationContext(AppConfig.class); anno.getBean(IndexDao.class).query(); }}运行打印query IndexDao for MyImportSelect

从上面的例子看,尽管程序上没有把MyImportSelect类放到Spring容器中,也没有把IndexDao放到Spring容器中,但是在测试上就可以把IndexDao从容器中拿出来,并且正常执行。

不知道大家看到这里有什么感觉,到这里我其实是有疑问的。我这么做有个卵用噻。我是有病吧,直接把类上加个@Component注册进去不香吗?所以这个ImportSelector把程序搞这么复杂是有毛病吧,把简单的功能搞这么复杂。

在这里插入图片描述

ImportSelector真正的作用

其实Spring公司既然这么设计,那肯定是有用的。那么有什么用呢?设想这样一个场景,如果有些功能我们并不需要Spring在一开始就加载进去,而是需要Spring帮助我们把这些功能动态加载进去,这时候这个ImportSelector的作用就来了。我们完全可以把实现这个接口的类做成一个开关,用来开启或者关闭某一个或者某些功能类。

比如说我们上面的例子IndexDao,假设这个IndexDao实现的功能是一个扩展功能,在正式的生产上不一定用的到。如果说一个包下有100个类,那么使用扫描去屏蔽这个类就很麻烦,但是屏蔽这个类用ImportSelector去做就很容易了。下次如果需要用到了,我再放开这个开关,直接可以使用IndexDao的功能了,这样就做到了一个灵活的功能掌控。

再举一个实际的用例,假设我们的IndexDao不是打印而是返回一个针对代理IndexDao3的代理对象,比如输出一个log。但是这个方法我不一定会用到,因为只有需要用到代理的时候,这个方法才有意义。我不需要去代理,这里的代码就不要运行。只有给一个显示的通知,我这个代理才会去执行。

public class IndexDao {
public void query(){
System.out.println("log for IndexDao3"); return Proxy.newProxyInstance(IndexDao3);//伪码 }}

看到这里,大家有没有联想到SpringAOP其实就是这个样子。能够做到动态加载与卸载,与我们的程序没有什么耦合关系。怎么才能实现这个所谓的动态开启呢?

ImportSelector开关

为了完成这个开关,我们也模仿Spring写一个EnableMySelector的注解,然后@Import我们自己的ImportSelector接口类。

@Retention(RetentionPolicy.RUNTIME) //开启运行时加载@Import(MyImportSelect.class)public @interface EnableMySelector {
}

做好了这一步在AppConfig这个配置里面就可以直接使用这个@ EnableMySelector自定义注解去开关一个类了。

@ComponentScan("com.demo")@EnableMySelectorpublic class AppConfig {
}运行,一样打印query IndexDao for MyImportSelect

讲道理其实Spring中那么多的EnableXXXX的注解底层就是这样的原理。到此还有谁敢说ImportSelector用处小?

在这里插入图片描述

连带说一下DeferredImportSelector

这个是看Spring源码的时候发现的,直接翻译就是延时加载ImportSelector,实现这个接口的类,将会在@Configuration后面被加载,用法什么的和ImportSelector功能基本一样。因为用的比较稀有就不多做解释了,仅仅作为一个只是扩展点介绍下。在ConfigurationClassParser中会有一个判断,是不是这个接口,如果是就会放到后面解析。以下摘自源码:

org.springframework.context.annotation.ConfigurationClassParser#processImports//这里拦截了DeferredImportSelector然后使用handle()if (selector instanceof DeferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);}

进入handle()方法,发现和这个接口相关的都被加入了一个deferredImportSelectors的list中。

public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(configClass, importSelector); if (this.deferredImportSelectors == null) {
DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler(); handler.register(holder); handler.processGroupImports(); } else {
//加入到了一个ArrayList中 this.deferredImportSelectors.add(holder); }}

最终这个ArrayList在parse()方法的最后被处理了

org.springframework.context.annotation.ConfigurationClassParser#parse(java.util.Set
)public void parse(Set
configCandidates) {
//根据BeanDefinition的类型做不同的处理,一般都会调用ConfigurationClassParser.parse()进行解析 for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition(); //拿出BeanDefinition try {
if (bd instanceof AnnotatedBeanDefinition) {
//判断是不是加了注解的 // 解析注解对象,并且把解析出来的bd方法map中,但是这里的bd指的的普通的 // 普通和不普通的怎么区分。比如@Bean和各种beanFactoryPostProcessor得到的bean //如果被加了注解,又调用了一个parse()方法 parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName()); } else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName()); } else {
parse(bd.getBeanClassName(), holder.getBeanName()); } } catch (BeanDefinitionStoreException ex) {
throw ex; } catch (Throwable ex) {
throw new BeanDefinitionStoreException( "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex); } } //处理,而此时上面其他的Import已经处理完了 this.deferredImportSelectorHandler.process();}

总结

不得不说Spring公司的大神们编程思想是真的厉害,但是这代码和注释写的是真的难以下咽。那么下一篇我们就说下另一个重要的@Import接口: ImportBeanDefinitionRegistrar。这个接口更加的厉害,它能够干预BeanDefinition注册过程,而且我们经常使用的大名鼎鼎的Mybatis就是根据这个接口和Spring框架进行的整合。最后感谢各位阅读到此。

转载地址:http://ttmsi.baihongyu.com/

你可能感兴趣的文章
poj 3276 Face The Right Way 挑战150 反转
查看>>
poj 3279 Fliptile 反转
查看>>
poj 3185 The Water Bowls 反转(开关)
查看>>
poj 1930 Dead Fraction 循环小数的处理
查看>>
poj 3421 X-factor Chains 素数筛选 因子分解
查看>>
poj 3292 Semi-prime H-numbers 素数变形+打表+筛选法
查看>>
poj 3468 A Simple Problem with Integers 模板题 线段树 懒惰标记
查看>>
POJ 3264 Balanced Lineup 线段树 维护区间最大值和最小值 建树
查看>>
poj 3368 Frequent values 线段树 节点值得变化
查看>>
poj 1201 Intervals 线段树+贪心
查看>>
hdu 2602 Bone Collector 0-1背包;
查看>>
CF #318 (Div. 2) C. Bear and Poker 唯一分解定理
查看>>
CF#318 (Div. 2)B. Bear and Three Musketeers 暴力 复杂度分析
查看>>
hdu 1421
查看>>
poj 3041 Asteroids 二分匹配 匈牙利算法 模板题
查看>>
poj 3281 Dining 最大流dinic 模板题
查看>>
poj 3469 Dual Core CPU 最大流建图思想 dinic 弧优化很重要
查看>>
poj 2135 Farm Tour 最小费用流 spfa优化 16_05_14
查看>>
poj 3686 The Windy\'s 最小费用流 建图 16_05_14
查看>>
poj 3168 Barn Expansion 平面扫描+线段相交问题
查看>>