从 Spring Boot application.yml 文件中注入 @Scheduled fixedRate 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27445702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject @Scheduled fixedRate value from Spring Boot application.yml file
提问by Juan Carlos González
I know I can inject the value from properties file with the following syntax:
我知道我可以使用以下语法从属性文件中注入值:
@Scheduled(fixedRate=${myRate})
public void getSchedule(){
System.out.println("in scheduled job");
}
However I can't guess how to accomplish the same if the configuration is in YAML file.
但是,如果配置在 YAML 文件中,我无法猜测如何完成相同的操作。
Thanks in advance,
提前致谢,
回答by Wajax
In my application.properties (YAML) I put this
在我的 application.properties (YAML) 我把这个
console:
fetchMetrics: 5000
Then in my simple Task class I push the definition :
然后在我的简单 Task 类中,我推送定义:
@Scheduled(fixedRateString ="${console.fetchMetrics}", initialDelay=1000)
public void fetchMetrics() {
logger.info("What's up ?");
}
Please notice that fixedRate
expects a long
and you want to inject a placeholder, you will need fixedRateString
请注意,fixedRate
期望 along
并且您要注入占位符,您将需要fixedRateString
回答by abhishek ringsia
I find it easy once done for my project.
Change fixedRate
to fixedRateString
and put the property key in double quotes
like this:
我发现我的项目完成后很容易。
更改fixedRate
到fixedRateString
而属性键double quotes
是这样的:
@Scheduled(fixedRateString="${myRate}")
public void getSchedule() {
System.out.println("Scheduled job");
}
回答by Dalila Serpa
In my application I use the annotation PropertySource
on my config class:
在我的应用程序中,我PropertySource
在我的配置类上使用了注释:
@PropertySource("application-${spring.profiles.active}.yml")
@PropertySource("application-${spring.profiles.active}.yml")
spring.profiles.active
returns the active profile (dev, test, etc). My properties file name is application-dev.yml
spring.profiles.active
返回活动配置文件(开发、测试等)。我的属性文件名是 application-dev.yml
The annotation @Scheduled
works with property injection.
Dont forget the annotation with prefix configuration on your class.
该注释@Scheduled
适用于属性注入。不要忘记类上带有前缀配置的注释。