且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是@ConditionalOnProperty注释的目的是什么?

更新时间:2022-05-02 16:07:15

注解用于有条件地创建一个Spring bean依赖于一个属性的配置。在使用您曾表示,如果 spring.social.auto连接的视图属性存在bean将只被创建的问题,它与假。这意味着,要创建的这个查看豆,你需要设置 spring.social.auto连接的视图属性,它必须有false以外的值。

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.

您可以找到这个注释的整个春季启动code碱基许多其他用途。另一个例子是:

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 属性存在并且比其它的值 AmqpAdmin 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.