@ConditionalOnProperty 有条件地工作

编程入门 行业动态 更新时间:2024-10-28 05:14: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 有条件地工作

本文发布于:2023-05-27 23:12:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/306145.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   工作   ConditionalOnProperty

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!