因为在上面没有看到直接的说明都不是很明确,所以给大家看看我的想法:
@ConditionalOnMissingBean
注解可以用于配置类或者 Bean 方法上,用来控制 Bean 的加载条件。当且仅当容器中不存在指定类型的 Bean 时,被标记的 Bean 才会被创建并加入到容器中。
进入@ConditionalOnMissingBean
查看解释:
@Conditional that only matches when no beans meeting the specified requirements are already contained in the BeanFactory. None of the requirements must be met for the condition to match and the requirements do not have to be met by the same bean.
When placed on a @Bean method, the bean class defaults to the return type of the factory method:
@Configuration
public class MyAutoConfiguration {
@ConditionalOnMissingBean
@Bean
public MyService myService() {
...
}
}
In the sample above the condition will match if no bean of type MyService is already contained in the BeanFactory.
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.
自:
1.0.0
作者:
Phillip Webb, Andy Wilkinson
转化为中文:
@Conditional仅当BeanFactory中已没有满足指定要求的Bean时才匹配。
条件匹配时不需要满足任何要求,相同的Bean也不必满足这些要求。
当放置在@Bean方法上时,Bean类默认为工厂方法的返回类型:
@配置。
公共类MyAutoConfiguration{。
@ConditionalOnMissingBean。
@Bean。
公共MyService myService(){。
..。
}。
}。
在上面的示例中,如果BeanFactory中没有包含类型为MyService的Bean,则条件将匹配。
该条件只能匹配到目前为止已由应用程序上下文处理的Bean定义,因此,强烈建议仅在自动配置类上使用该条件。
如果候选Bean可能是由另一个自动配置创建的,请确保使用此条件的Bean在之后运行。
自:
1.0.0。
作者:
菲利普·韦伯,安迪·威尔金森
@Bean
@ConditionalOnMissingBean(RedisConnectionDetails.class)
PropertiesRedisConnectionDetails redisConnectionDetails(RedisProperties properties) {
return new PropertiesRedisConnectionDetails(properties);
}
@ConditionalOnMissingBean(RedisConnectionDetails.class)
表示当容器中不存在类型为 RedisConnectionDetails
的 Bean 时,才会创建被该注解标记的 Bean。