控制配置类的加载顺序@AutoConfigureAfter

当您的项目处在以下情况的时候,我觉得这篇文章对您有一些帮助

  1. 使用Springboot 1.5.4 及以上 (本人没有用过更低版本)
  2. 自动装配不能满足您的需求,需要自己简单的控制配置类加载顺序

@AutoConfigureAfter 是 spring-boot-autoconfigure包下的注解
其作用顾名思义,就是将一个配置类在另一个配置类之后加载。

研究初衷:
本人公司使用了Pagehelper,它的实现原理是Mybatis Plugin,也就是拦截器。根据拦截器的加载机制,后加载的先执行(在另一篇文章中会详细介绍Mybatis拦截器,这里讲的并不全面),由于某种原因,我需要在他之前拦截到SQL语句,这就要求拦截器要加载在Pagehelper之后。

只需要两步

  1. 第一步,创建配置类,使用@AutoConfigureAfter注解,注解内写明在哪一个配置类之后执行。
@Configuration
@AutoConfigureAfter({PageHelperAutoConfiguration.class})
public class DataPermissionConfig {
}
  1. 第二步,在项目的 resources 目录下,创建 META-INF 目录(如果已有,不用创建),在 META-INF 目录下创建 spring.factories 文件,文件中写入以下内容。
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration,\
com.xxx.xxx.xxx.xxx.config.DataPermissionConfig

等号后面是配置类的路径,用逗号 "," 隔开。

除了@AutoConfigureAfter,spring-boot-autoconfigure下还有很多类似注解,如:@AutoConfigureBefore、@AutoConfigureOrder等。有兴趣的可以多加研究,其实现原理基本都是在 getInPriorityOrder() 方法中通过 ASCII、Sort值、before/after 来排序的。源码如下:

public List<String> getInPriorityOrder(Collection<String> classNames) {
        final AutoConfigurationSorter.AutoConfigurationClasses classes = new AutoConfigurationSorter.AutoConfigurationClasses(this.metadataReaderFactory, this.autoConfigurationMetadata, classNames);
        List<String> orderedClassNames = new ArrayList(classNames);
        // 首先根据ASCII来进行排序
        Collections.sort(orderedClassNames);
        // 根据 Order
        Collections.sort(orderedClassNames, new Comparator<String>() {
            public int compare(String o1, String o2) {
                int i1 = classes.get(o1).getOrder();
                int i2 = classes.get(o2).getOrder();
                return i1 < i2 ? -1 : (i1 > i2 ? 1 : 0);
            }
        });
        // 根据 @AutoConfigureAfter @AutoConfigureBefore
        List<String> orderedClassNames = this.sortByAnnotation(classes, orderedClassNames);
        return orderedClassNames;
    }


以上均为个人理解,如有不足之处,欢迎在评论区留言。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容