What is purpose of @ConditionalOnProperty annotation?

http://stackoverflow.com/questions/26394778/what-is-purpose-of-conditionalonproperty-annotation

****************************************************

just modified spring boot configuration, and encountered

@ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views") from org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration.java 

        @Bean(name = { "connect/twitterConnect", "connect/twitterConnected" })
        @ConditionalOnProperty(prefix = "spring.social.", value = "auto-connection-views")
        public View twitterConnectView() {
            return new GenericConnectionStatusView("twitter", "Twitter");
        }

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").


answers

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.

如果property spring.social.auto-connection-views存在,并且值不为false,创建bean.

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);
}

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.

如果property spring.rabbitmq.dynamic存在,并且值不为false,创建bean

matchIfMissing = true, 如果改属性条目不存在,创建bean.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值