gpt4 book ai didi

spring-boot - @ConditionalOnProperty 有条件地起作用

转载 作者:行者123 更新时间:2023-12-02 04:49:55 25 4
gpt4 key购买 nike

我有如下代码:

@Scheduled(cron = "${cron.foo.bar}")
@ConditionalOnProperty(name="cron.foo.bar.enabled", relaxedNames = false)
public void parseFooBar() {
... blah blah blah ...
}

在我的属性文件中,我有:

cron.foo.bar=1 * * * * ?
cron.foo.bar.enabled=false

这不起作用,parseFooBar 会在每分钟的第一秒执行一次。

但是,如果我添加该字段:

@Value("${cron.foo.bar.enabled}")
private String enabledProp;

这样我就可以记录日志并查看它是什么,parseFooBar 不会被执行。再次删除注入(inject)的 String 会看到 parseFooBar 执行。我做错了什么?

编辑:这是使用 Spring 4.1.5、Spring Boot 1.2.1 和 JDK 8

编辑 2:将注释移动到类型也可以。 (无需强制@Value)。但该注解既是方法又是类型注解?它给了我更多的灵 active 来在方法上做到这一点......

最佳答案

Spring框架中的条件用于控制组件是否在应用程序上下文中注册。来自@Conditional的javadoc:

The @Conditional annotation may be used in any of the following ways:

  • as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes
  • as a meta-annotation, for the purpose of composing custom stereotype annotations
  • as a method-level annotation on any @Bean method

当在 parseFooBar 上声明条件时,它没有任何效果,因为它不是 @Bean 方法。当您在类型上声明它时,它会按照您的预期工作,因为它会使组件成为有条件的,这样当属性不匹配时,它就不会在应用程序上下文中注册。

关于spring-boot - @ConditionalOnProperty 有条件地起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com