Spring Boot AutoConfig的顺序

前文讲了Springboot Configuration 和 AutoConfiguraton ,我们可以得到如下的一些rule

  • Autoconfig 一定不能再@ComponentScan 的路径里。这会使Autoconfig的顺序难以保证。
    -避免@ConditionalOnXXX annotation在autoconfig 以外的类使用。
  • 在SpringBoot 1.3 以后,@Ordered 不能再@Configuration 的类上使用。

Autoconfig 加载的注意事项

@ComponentScan不在同一个包下:

  • spring.factories 中定义了autoConfig 会被加载
  • spring.factories 没有定义autoConfig, 不会被加载
      - 如果其他@Configuration类@Import了这个autoConfig, 会被加载
      - 其他@Configuration中@Autowire了spring.factories生成的@Bean, 导致提前初始化

@ComponentScan同一包名下

  • 不管spring.factories中有没有定义,扫描到后立即加载

SpringBoot 的预防

从上文可知,指定扫描的包名,请千万不要扫描到形如org.springframework这种包名,否则“天下大乱” 。 为了防止这种情况出现,Spring Boot做了容错的。它有一个类专门检测这个case防止你配置错了,具体参见ComponentScanPackageCheck预设实现。

具体请看spring-boot-2.3.3.RELEASE.jar

org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
...

具体看代码

public class ConfigurationWarningsApplicationContextInitializer
        implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private static final Log logger = LogFactory.getLog(ConfigurationWarningsApplicationContextInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext context) {
        context.addBeanFactoryPostProcessor(new ConfigurationWarningsPostProcessor(getChecks()));
    }

    /**
     * Returns the checks that should be applied.
     * @return the checks to apply
     */
    protected Check[] getChecks() {
        return new Check[] { new ComponentScanPackageCheck() };
    }

    /**
     * {@link BeanDefinitionRegistryPostProcessor} to report warnings.
     */
    protected static final class ConfigurationWarningsPostProcessor
            implements PriorityOrdered, BeanDefinitionRegistryPostProcessor {

        private Check[] checks;

        public ConfigurationWarningsPostProcessor(Check[] checks) {
            this.checks = checks;
        }

        @Override
        public int getOrder() {
            return Ordered.LOWEST_PRECEDENCE - 1;
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            for (Check check : this.checks) {
                String message = check.getWarning(registry);
                if (StringUtils.hasLength(message)) {
                    warn(message);
                }
            }

        }

        private void warn(String message) {
            if (logger.isWarnEnabled()) {
                logger.warn(String.format("%n%n** WARNING ** : %s%n%n", message));
            }
        }

    }

    /**
     * A single check that can be applied.
     */
    @FunctionalInterface
    protected interface Check {

        /**
         * Returns a warning if the check fails or {@code null} if there are no problems.
         * @param registry the {@link BeanDefinitionRegistry}
         * @return a warning message or {@code null}
         */
        String getWarning(BeanDefinitionRegistry registry);

    }

    /**
     * {@link Check} for {@code @ComponentScan} on problematic package.
     */
    protected static class ComponentScanPackageCheck implements Check {

        private static final Set<String> PROBLEM_PACKAGES;

        static {
            Set<String> packages = new HashSet<>();
            packages.add("org.springframework");
            packages.add("org");
            PROBLEM_PACKAGES = Collections.unmodifiableSet(packages);
        }

        @Override
        public String getWarning(BeanDefinitionRegistry registry) {
            Set<String> scannedPackages = getComponentScanningPackages(registry);
            List<String> problematicPackages = getProblematicPackages(scannedPackages);
            if (problematicPackages.isEmpty()) {
                return null;
            }
            return "Your ApplicationContext is unlikely to start due to a @ComponentScan of "
                    + StringUtils.collectionToDelimitedString(problematicPackages, ", ") + ".";
        }

        protected Set<String> getComponentScanningPackages(BeanDefinitionRegistry registry) {
            Set<String> packages = new LinkedHashSet<>();
            String[] names = registry.getBeanDefinitionNames();
            for (String name : names) {
                BeanDefinition definition = registry.getBeanDefinition(name);
                if (definition instanceof AnnotatedBeanDefinition) {
                    AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition;
                    addComponentScanningPackages(packages, annotatedDefinition.getMetadata());
                }
            }
            return packages;
        }

        private void addComponentScanningPackages(Set<String> packages, AnnotationMetadata metadata) {
            AnnotationAttributes attributes = AnnotationAttributes
                    .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true));
            if (attributes != null) {
                addPackages(packages, attributes.getStringArray("value"));
                addPackages(packages, attributes.getStringArray("basePackages"));
                addClasses(packages, attributes.getStringArray("basePackageClasses"));
                if (packages.isEmpty()) {
                    packages.add(ClassUtils.getPackageName(metadata.getClassName()));
                }
            }
        }

        private void addPackages(Set<String> packages, String[] values) {
            if (values != null) {
                Collections.addAll(packages, values);
            }
        }

        private void addClasses(Set<String> packages, String[] values) {
            if (values != null) {
                for (String value : values) {
                    packages.add(ClassUtils.getPackageName(value));
                }
            }
        }

        private List<String> getProblematicPackages(Set<String> scannedPackages) {
            List<String> problematicPackages = new ArrayList<>();
            for (String scannedPackage : scannedPackages) {
                if (isProblematicPackage(scannedPackage)) {
                    problematicPackages.add(getDisplayName(scannedPackage));
                }
            }
            return problematicPackages;
        }

        private boolean isProblematicPackage(String scannedPackage) {
            if (scannedPackage == null || scannedPackage.isEmpty()) {
                return true;
            }
            return PROBLEM_PACKAGES.contains(scannedPackage);
        }

        private String getDisplayName(String scannedPackage) {
            if (scannedPackage == null || scannedPackage.isEmpty()) {
                return "the default package";
            }
            return "'" + scannedPackage + "'";
        }

    }

}

Spring Boot下控制配置执行顺序

Spring Boot下对自动配置根据当前容器内的情况来动态的判断自动配置类的载入与否、以及载入的顺序,因此Spring Boot的自动配置它对顺序是有要求的。pring Boot给我们提供了@AutoConfigureBefore、@AutoConfigureAfter、@AutoConfigureOrder(下面统称这三个注解为“三大注解”)这三个注解来帮我们解决这种诉求。

需要注意的是:三大注解是Spring Boot提供的而非Spring Framework。其中前两个是1.0.0就有了,@AutoConfigureOrder属于1.3.0版本新增,表示绝对顺序(数字越小,优先顺序越高)。另外,这几个注解另外,这几个注解并不互斥,可以同时标注在同一个@Configuration自动配置类上。

三大注解解析时机浅析

AutoConfigureBefore 、AutoConfigureAfter 和 AutoConfigureOrder这三个注解的解析都是交给AutoConfigurationSorter来排序、处理的,做法类似于AnnotationAwareOrderComparator去解析排序@Order注解。排序算法 org.springframework.boot.autoconfigure.AutoConfigurationSorter#doSortByAfterAnnotation

class AutoConfigurationSorter {

    // 唯一給外部呼叫的方法:返回排序好的Names,因此返回的是個List嘛(ArrayList)
    List<String> getInPriorityOrder(Collection<String> classNames) {
        ...
        // 先按照自然順序排一波
        Collections.sort(orderedClassNames);
        // 在按照@AutoConfigureBefore這三個註解排一波
        orderedClassNames = sortByAnnotation(classes, orderedClassNames);
        return orderedClassNames;
    }
    ...
}

AutoConfigurationImportSelector:Spring自动配置处理器,用于载入所有的自动配置类。它实现了DeferredImportSelector介面:这也顺便解释了为何自动配置是最后执行的原因

        private List<String> sortAutoConfigurations(Set<String> configurations,
                AutoConfigurationMetadata autoConfigurationMetadata) {
            return new AutoConfigurationSorter(getMetadataReaderFactory(), autoConfigurationMetadata)
                    .getInPriorityOrder(configurations);
        }

AutoConfigurations:表示自动配置@Configuration类。

    protected Collection<Class<?>> sort(Collection<Class<?>> classes) {
        List<String> names = classes.stream().map(Class::getName).collect(Collectors.toList());
        List<String> sorted = SORTER.getInPriorityOrder(names);
        return sorted.stream().map((className) -> ClassUtils.resolveClassName(className, null))
                .collect(Collectors.toCollection(ArrayList::new));
    }

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容