What is purpose of @ConditionalOnProperty annotation?

后端 未结 3 1744
庸人自扰
庸人自扰 2020-12-04 14:19

I just modified spring boot configuration, and encountered

@ConditionalOnProperty(prefix = \"spring.social.\", value = \"auto-connection-views\") 


        
相关标签:
3条回答
  • 2020-12-04 14:26

    Rather, it is the opposite. A precondition for implementing the method, if the property is set in the environment (development, approval, production) and is true value with the method can be executed.

    If the property is not set in the environment annotation not prevented the execution of the method.

    0 讨论(0)
  • 2020-12-04 14:37

    In case you are using this property on TYPE-level, i.e. on one of your @Configuration classes... Keep in mind that in such case the annotation is evaluated/checked against the default properties file, i.e. application.properties

    @ConditionalOnProperty on TYPE level w/ @Configuration

    0 讨论(0)
  • 2020-12-04 14:51

    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.

    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.

    0 讨论(0)
提交回复
热议问题