@ConditionalOnProperty 注释的目的是什么? [英] What is purpose of @ConditionalOnProperty annotation?
问题描述
我刚刚修改了spring boot的配置,遇到了
I just modified spring boot configuration, and encountered
@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
来自 org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration
@Bean(name = { "connect/twitterConnect", "connect/twitterConnected" })
@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
public View twitterConnectView() {
return new GenericConnectionStatusView("twitter", "Twitter");
}
我不明白这个注释的目的.我想这可能只有在属性值存在时才能使用 bean(例如spring.social"、auto-connection-views").
I don't understand purpose of this annotation. I guess this might be enable to use bean only if property value exist(e.g. "spring.social", "auto-connection-views").
推荐答案
注解用于根据属性的配置有条件地创建 Spring bean.在您在问题中显示的用法中,仅当 spring.social.auto-connection-views
属性存在且其值不是 false
时才会创建 bean>.这意味着,要创建此 View
bean,您需要设置 spring.social.auto-connection-views
属性,并且它必须具有除假的.
The annotation is used to conditionally create a Spring bean depending on the configuration of a property. In the usage you've shown in the question the bean will only be created if the spring.social.auto-connection-views
property exists and it has a value other than false
. This means that, for this View
bean to be created, you need to set the spring.social.auto-connection-views
property and it has to have a value other than false.
您可以在整个 Spring Boot 代码库中找到此注释的许多其他用途.另一个例子是:
You can find numerous other uses of this annotation throughout the Spring Boot code base. Another example is:
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "dynamic", matchIfMissing = true)
public AmqpAdmin amqpAdmin(CachingConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
注意matchIfMissing
的使用.在这种情况下,如果 spring.rabbitmq.dynamic
属性存在并且其值不是 false
或 该属性根本不存在.这使得 bean 的创建选择退出,而不是问题中选择加入的示例.
Note the use of matchIfMissing
. In this case the AmqpAdmin
bean will be created if the spring.rabbitmq.dynamic
property exists and has a value other than false
or the property doesn't exist at all. This makes the creation of the bean opt-out rather than the example in the question which is opt-in.
这篇关于@ConditionalOnProperty 注释的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!