@ConditiontionalOnBean和@ConditiontionalOnMissingBean注解使用
1、介绍
1.1、@ConditiontionalOnBean
官方文档:
The condition can only match the bean definitions that have been processed by the
application context so far and, as such, it is strongly recommended to use this
condition on auto-configuration classes only. If a candidate bean may be created by
another auto-configuration, make sure that the one using this condition runs after.
如果容器有xxx.class才会注入
1.2、@ConditiontionalOnMissingBean
官方文档:
The condition can only match the bean definitions that have been processed by the
application context so far and, as such, it is strongly recommended to use this
condition on auto-configuration classes only. If a candidate bean may be created by
another auto-configuration, make sure that the one using this condition runs after.
和@ConditiontionalOnBean相反,如果容器中没有xxx.class才会注入Bean
2、实战
Bean:
@Data
@AllArgsConstructor
public class Computer {
/**
* 名称
*/
private String name;
}
@Configuration
public class ConditionalOnMissingBeanAutoConfiguration {
// @Bean(name = "notebookPc")
// public Computer computer1(){
// return new Computer("笔记本电脑");
// }
@ConditionalOnBean(Computer.class)
// @ConditionalOnMissingBean(Computer.class)
@Bean(name = "pad")
public Computer computer2(){
return new Computer("平板电脑");
}
}
@RestController("/conditionalBean")
public class ConditionalOnBeanController {
@Autowired
private Computer computer;
@GetMapping("/getConditionalOnBean")
public String getConditionalOnBean(){
return computer.getName();
}
}
3、猜测
- 单使用@ConditionOnBean
- 单使用@ConditionOnMissingBean
- @ConditionOnBean先注册computer1再注册computer2
- @ConditionOnMissingBean先注册computer1再注册computer2
- @ConditionOnBean先注册keyBoard.class再注册computer2
- 两个注解能否同时使用?
4、验证
4.1、单使用@ConditionOnBean
结果:启动失败
原因:需要提前加载Computer.class
4.2、单使用@ConditionOnMissingBean
启动成功:
通过接口能访问并拿到Bean的name为平板电脑
4.3、@ConditionOnBean先注册computer1再注册computer2
结果:GG,由于Spring的Bean是一个单例对象,所以不能注入两个
4.4、@ConditionOnMissingBean先注册computer1再注册computer2
结构:成功!访问的Bean是笔记本电脑
4.5、@ConditionOnBean先注册keyBoard.class再注册computer2
结果成功:
4.6、两个注解能否同时使用?
结果:可以。
5、源码分析
占位!!!
6、总结
由上面六种情况可以看出
- @ConditionOnBean必须在xxx.class Bean类存在时才可以进行注入
- @ConditionOnMissingBean是在xxx.class Bean类存在时将注入的Bean省略掉,如果不存在则进行注入。
- 两者可以一起使用,其核心还是Contional是否满足要求。