Springboot中的@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,就是当前上下文

然后就对着上下文一顿操作,返回结果.
到此这篇关于Springboot中的@ConditionalOnBean注解详细解读的文章就介绍到这了,更多相关@ConditionalOnBean注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
