@ConditionalOnProperty 有条件地工作 [英] @ConditionalOnProperty conditionally works

查看:38
本文介绍了@ConditionalOnProperty 有条件地工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码:

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

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

In my properties file, I have:

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

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

This does not work, and parseFooBar gets executed every minute on the 1st second.

但是,如果我添加字段:

However, if I add the field:

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

这样我就可以做一个日志并查看它是什么,parseFooBar 不会被执行.再次删除注入的 String 会看到 parseFooBar 执行.我做错了什么?

so that I can do a log and see what it is, parseFooBar does NOT get executed. Removing the injected String once again sees parseFooBar execute. What am I doing wrong?

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

This is using Spring 4.1.5, Spring Boot 1.2.1, and JDK 8

编辑 2:将注释移动到类型也有效.(无需强制@Value).但是注解既是方法又是类型注解?它让我在方法上更灵活一些...

Edit 2: moving the annotation to the type also works. (without having to force the @Value). But the annotation is both a Method and a Type annotation? It gives me a little more flexibility to do it on the method...

推荐答案

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

A condition in Spring Framework is used to control whether or not a component is registered in the application context. From the javadoc of @Conditional:

@Conditional 注释可以通过以下任何一种方式使用:

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

  • 作为直接或间接用@Component注解的任何类上的类型级注解,包括@Configuration
  • 作为元注释,用于编写自定义构造型注释
  • 作为任何 @Bean 方法的方法级注解
  • 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 方法.当您在类型上声明它时,它会按您的预期工作,因为它会使组件有条件,以便在属性不匹配时不会在应用程序上下文中注册.

When the condition is declared on parseFooBar it has no effect as it's not a @Bean method. It works as you expect when you declare it on the type as it then makes the component conditional such that it's not registered in the application context when the property doesn't match.

这篇关于@ConditionalOnProperty 有条件地工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆