Spring框架的ImportSelector到底可以干嘛

前言

最近一直在钻研Spring源码,感觉要把自己看吐了,但是看到奥妙的地方还是会拍手称快。这次就总结一下Spring中一个非常重要的注解@Import中的ImportSelector接口的作用以及它到底有啥作用。也会捎带一部分源码说一下DeferredImportSelector是干啥的,以及Spring解析这个和ImportSelector有什么区别。更多Spring内容进入【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<String> 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(IndexDao3.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")
@EnableMySelector
public 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<org.springframework.beans.factory.config.BeanDefinitionHolder>)

public void parse(Set<BeanDefinitionHolder> 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公司的大神们编程思想是真的厉害,但是这代码和注释写的是真的难以下咽。那么下一篇【Spring框架中ImportBeanDefinitionRegistrar和ImportSelector的区别】我们就说下另一个重要的@Import接口: ImportBeanDefinitionRegistrar。这个接口更加的厉害,它能够干预BeanDefinition注册过程,而且我们经常使用的大名鼎鼎的Mybatis就是根据这个接口和Spring框架进行的整合。最后感谢各位阅读到此。

猜你喜欢

转载自blog.csdn.net/Smallc0de/article/details/108619562
今日推荐