美文网首页
SpringBoot自动配置初探

SpringBoot自动配置初探

作者: RobertCrazying | 来源:发表于2018-03-12 22:56 被阅读106次

    前言

    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 标注它使得不会出错。

    相关文章

      网友评论

          本文标题:SpringBoot自动配置初探

          本文链接:https://www.haomeiwen.com/subject/kwiofftx.html