SpringBoot自动配置初探

前言

Spring Boot 刚发布 2.0 正式版,是当前微服务架构最热门的框架了。其大幅地简化了配置,开箱即用的特性深受人喜爱。下面我来稍微讲下其中一部分奥秘

条件注解

Spring 4 版本开始提供了一个条件注解 @Conditional ,它的进化版 @ConditionalOnBean 、@ConditionalOnMissBean 等在 Spring Boot 的各个 starter 里面大行其道。下面来看下这些注解的简单用法。

首先自定义一个条件类:

public class WindowsCondition implements Condition{
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
        return context.getEnvironment().getProperty("os.name").contains("Windows");
    }
}

生成 Bean 时指定条件:

    @Bean
    @Conditional(WindowsCondition.class)
    public Object windowsBean(){
        return new Object();
    }

这样在生成 bean id 为 object 的 bean 对象时就会根据当前的系统变量来确定是否生成。注意 @Bean 也是 Spring 4 版本后提供的一个注解,作用相当于配置文件里面的 bean 定义。同样也是 Spring Boot 各个 starter 里面的宠儿。

复合条件注解

@ConditionalOnBean的用法是仅仅在当前上下文中存在某个对象时,才会实例化一个 Bean,接下来看下例子:

    /** 
     * 存在 Abc 类的实例时 
     */  
    @ConditionalOnBean(Abc.class)  
    @Bean  
    public String bean() {  
        System.err.println("ConditionalOnBean is exist");  
        return "";  
    }  

意思是只有 Abc 这个 Bean 示例存在才会继续 实例化 bean 这个示例。
接着来看下 @ConditionalOnBean 的源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure.condition;

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Conditional;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional({OnBeanCondition.class})
public @interface ConditionalOnBean {
    Class<?>[] value() default {};

    String[] type() default {};

    Class<? extends Annotation>[] annotation() default {};

    String[] name() default {};

    SearchStrategy search() default SearchStrategy.ALL;
}

可以看到它其实是指定了条件类为 OnBeanCondition 。这里也显示 Spring Boot 没有一些相对于前面版本的新特性而是把 Spring 前面几个版本的最佳实践做了很好的封装。

接下来开始解读 OnBeanCondition 的源码:
先看类图关系:


image.png

可以看到 OnBeanCondition 继承自 SpringBootCondition 类,下面看下这个类的源码:
直接看其实现 Condition 接口的 matches 方法

    public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String classOrMethodName = getClassOrMethodName(metadata);

        try {
            ConditionOutcome outcome = this.getMatchOutcome(context, metadata);
            this.logOutcome(classOrMethodName, outcome);
            this.recordEvaluation(context, classOrMethodName, outcome);
            return outcome.isMatch();
        } catch (NoClassDefFoundError var5) {
            throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + var5.getMessage() + " not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)", var5);
        } catch (RuntimeException var6) {
            throw new IllegalStateException("Error processing condition on " + this.getName(metadata), var6);
        }
    }

主要逻辑是根据 metadata 元数据找到被标注的类或方法的匹配的出口outcome。这个 SpringBootCondition 是个大基类,翻看代码可以看到有几十个类继承了它,这个 getMatchOutcome 是个抽象方法 ,OnBeanCondition 就实现了它,下面看下源码:

    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConditionMessage matchMessage = ConditionMessage.empty();
        OnBeanCondition.BeanSearchSpec spec;
        List matching;
        if(metadata.isAnnotated(ConditionalOnBean.class.getName())) {
            spec = new OnBeanCondition.BeanSearchSpec(context, metadata, ConditionalOnBean.class);
            matching = this.getMatchingBeans(context, spec);
            if(matching.isEmpty()) {
                return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnBean.class, new Object[]{spec}).didNotFind("any beans").atAll());
            }

            matchMessage = matchMessage.andCondition(ConditionalOnBean.class, new Object[]{spec}).found("bean", "beans").items(Style.QUOTE, matching);
        }       
        return ConditionOutcome.match(matchMessage);
    }

这里以 ConditionalOnBean 为例,其余代码先省略,可以看到主要逻辑在 getMatchingBeans 这里。接下来再看下源码:

    private List<String> getMatchingBeans(ConditionContext context, OnBeanCondition.BeanSearchSpec beans) {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        if(beans.getStrategy() == SearchStrategy.PARENTS || beans.getStrategy() == SearchStrategy.ANCESTORS) {
            BeanFactory parent = beanFactory.getParentBeanFactory();
            Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent, "Unable to use SearchStrategy.PARENTS");
            beanFactory = (ConfigurableListableBeanFactory)parent;
        }

        if(beanFactory == null) {
            return Collections.emptyList();
        } else {
            List<String> beanNames = new ArrayList();
            boolean considerHierarchy = beans.getStrategy() != SearchStrategy.CURRENT;
            Iterator var6 = beans.getTypes().iterator();

            String beanName;
            while(var6.hasNext()) {
                beanName = (String)var6.next();
                beanNames.addAll(this.getBeanNamesForType(beanFactory, beanName, context.getClassLoader(), considerHierarchy));
            }

            var6 = beans.getIgnoredTypes().iterator();

            while(var6.hasNext()) {
                beanName = (String)var6.next();
                beanNames.removeAll(this.getBeanNamesForType(beanFactory, beanName, context.getClassLoader(), considerHierarchy));
            }

            var6 = beans.getAnnotations().iterator();

            while(var6.hasNext()) {
                beanName = (String)var6.next();
                beanNames.addAll(Arrays.asList(this.getBeanNamesForAnnotation(beanFactory, beanName, context.getClassLoader(), considerHierarchy)));
            }

            var6 = beans.getNames().iterator();

            while(var6.hasNext()) {
                beanName = (String)var6.next();
                if(this.containsBean(beanFactory, beanName, considerHierarchy)) {
                    beanNames.add(beanName);
                }
            }

            return beanNames;
        }
    }

这里首先会判断 @ConditionalOnBean 有没有指定 SearchStrategy 搜索策略,如果是 PARENTS 或 ANCESTORS 即父类或祖先则判断是否存在父级 BeanFactory ,没有则直接返回 null ,这里在 ConditionalOnBean 的配置项都有体现,如对于 type 直接在 beanFactory 搜索是否存在 bean ,ignored 则忽略相应的 bean。

总结

本文稍微探讨了一下 Spring Boot 的条件配置,使用场景例如某些 Bean 依赖数据源 DataSource ,这样就可以用 @ConditionalOnBean 标注它使得不会出错。

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

推荐阅读更多精彩内容