@ConditiontionalOnBean和@ConditiontionalOnMissingBean注解使用

@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是否满足要求。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值