@ConditionalOnBean 与@ConditionalOnMissingBean
时间: 2023-11-14 19:56:50 浏览: 52
@ConditionalOnBean和@ConditionalOnMissingBean注解都是Spring框架中的条件注解,用于在配置类中根据特定条件来决定是否创建某个Bean。
@ConditionalOnBean注解的作用是:只有当容器中存在指定的Bean时,才会创建被注解的Bean。可以理解为,它是一个创建Bean的条件。
@ConditionalOnMissingBean注解的作用是:只有当容器中不存在指定的Bean时,才会创建被注解的Bean。可以理解为,它是一个不创建Bean的条件。
这两个注解都是@Conditional注解的派生注解,可以通过指定不同的条件来控制Bean的创建与否。这些条件可以是一个或多个Spring提供的内置条件,也可以是自定义的条件。
总结起来,@ConditionalOnBean用于当容器中存在指定的Bean时创建被注解的Bean,而@ConditionalOnMissingBean用于当容器中不存在指定的Bean时创建被注解的Bean。这两个注解都是通过@Conditional注解来实现条件控制的。
参考资料:
@ConditionalOnBean and @ConditionalOnMissingBean in Spring Boot. Available at: https://www.baeldung.com/spring-boot-conditionalonbean
相关问题
2>:@ConditionalOnBean与@ConditionalOnMissingBean
@ConditionalOnBean 和 @ConditionalOnMissingBean 是 Spring Framework 中的注解,用于控制 Bean 的创建条件。
@ConditionalOnBean 注解用于指定在存在指定的 Bean 时才创建当前的 Bean。它接受一个或多个 Class 类型的参数,表示需要存在的 Bean 的类型。当所有指定的 Bean 都存在时,才会创建被注解的 Bean。
@ConditionalOnMissingBean 注解与 @ConditionalOnBean 相反,用于指定在不存在指定的 Bean 时才创建当前的 Bean。同样,它也接受一个或多个 Class 类型的参数,表示需要不存在的 Bean 的类型。当所有指定的 Bean 都不存在时,才会创建被注解的 Bean。
这两个注解通常与 @Configuration 和 @Bean 注解一起使用,用于控制条件化的 Bean 创建。可以根据应用需求,按照不同的条件来创建不同的 Bean 实例,并且避免冲突或重复创建相同类型的 Bean。
spring @ConditionalOnMissingBean(MqttClientPersistence.class)作用
@ConditionalOnMissingBean(MqttClientPersistence.class)是Spring Boot中的一个条件注解,它的作用是当给定的bean不存在时,才会实例化当前的bean。在这个例子中,当MqttClientPersistence类不存在时,才会实例化当前的bean。这个注解通常用于避免重复实例化bean,或者在某些情况下需要根据条件来实例化bean的情况下使用。
举个例子,如果我们在项目中需要使用MqttClientPersistence类来实现某些功能,但是这个类可能并不是所有的环境都存在,那么我们就可以使用@ConditionalOnMissingBean注解来判断这个类是否存在,如果不存在,则实例化当前的bean,否则不实例化。
另外,@ConditionalOnMissingBean注解还可以和@ConditionalOnBean注解一起使用,用于判断某个bean是否存在,从而决定是否实例化当前的bean。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)