@ConditionalOnBean详解

为啥要学习@ConditionalOnBean

在学习springboot自动装配的时候发现有用到@Conditional@ConditionalOnBean注解,当时只是了解大概,平常用的不多,但是后来想了解一下,看到网上有详解了,就自己跟着走了一遍,受益匪浅.了解了@Conditional注解,在学习@ConditionalOnBean注解,效果更佳哦!

@ConditionalOnMissingBean测试

首先学习:
@ConditionalOnMissingBean注解
两个类,一个Computer类,一个配置类,想要完成;如果容器中没有Computer类,就注入备用电脑Computer类,如果有Computer就不注入;

computer类:

@Data
@AllArgsConstructor
public class Computer {

    public String name;

}

配置类:


import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

//    @Bean(name = "notebookPC")
    public Computer computer1() {
        return new Computer("笔记本电脑");
    }

//    @ConditionalOnBean(Computer.class)
    @ConditionalOnMissingBean(Computer.class)
    @Bean("notebookPC")
    public Computer computer2() {
        return new Computer("备用电脑");
    }
}

测试启动类:
在这里插入图片描述

public class ConditionOnBeanTest extends BaseTest implements ApplicationContextAware {

    @Test
    public void test1() {
        Map<String, Computer> beansOfType = ApplicationContext.getBeansOfType(Computer.class);

        System.out.println(JSON.toJSONString(beansOfType));

    }

    public ApplicationContext ApplicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ApplicationContext = applicationContext;
    }
}

执行测试类:
在这里插入图片描述
容器中加载的是笔记本,将笔记本去掉走一波:
在这里插入图片描述
容器中注入的是备用电脑,很明了…
在这里插入图片描述

再来讲@ConditionalOnBean

再来讲@ConditionalOnBean注解就会很简单,跟@ConditionalOnMissingBean相反。
@ConditionalOnBean注解是,如果有容器中有Computer类,就注入备用电脑Computer类,如果有Computer就不注入;可以自己换个注解试一下就知道了,

源码分析

一起看下@ConditionalOnMissingBean的声明:
在这里插入图片描述
@Condition注解使用的是OnBeanCondition类,我们就看下这个类.这个类继承FilteringSpringBootCondition,就看继承的,FilteringSpringBootCondition又继承SpringBootCondition,点到SpringBootCondition,看到了我们熟悉的方法,matches方法.
在这里插入图片描述
在这里插入图片描述
我们一起看看matche方法
在这里插入图片描述
看最重要的方法的实现;
在这里插入图片描述
主要就在这个方法里面:
在这里插入图片描述
返回的对象:
在这里插入图片描述
getMatchingBeans方法比较复杂,也比较简单,就是根据当前上下文容器,查找是否存在对应的类,SearchStrategy 这个枚举定义了搜索的范围,All就是搜索整个上下文,父子容器等等,ANCESTORS搜索所有祖先,除开当前上下文,CURRENT,就是当前上下文
在这里插入图片描述
然后就对着上下文一顿操作,返回结果.

自己测试源码

https://github.com/stackXu/study-authconfigure

原文作者

两篇都是一个哥们的,总结的很通俗易懂,已点赞.加感谢,但是不自己跟着走一遍印象不深,故自己跟着走一波
转:
https://blog.csdn.net/xcy1193068639/article/details/81517456
https://www.jianshu.com/p/c4df7be75d6e

posted @ 2019-06-27 21:50  你就像甜甜的益达  阅读(727)  评论(0编辑  收藏  举报