从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:15:35  来源:igfitidea点击:

Inject @Scheduled fixedRate value from Spring Boot application.yml file

springspring-boot

提问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 fixedRateexpects a longand 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 fixedRateto fixedRateStringand put the property key in double quoteslike this:

我发现我的项目完成后很容易。
更改fixedRatefixedRateString而属性键double quotes是这样的:

@Scheduled(fixedRateString="${myRate}")
public void getSchedule() {
    System.out.println("Scheduled job");
}

回答by Dalila Serpa

In my application I use the annotation PropertySourceon my config class:

在我的应用程序中,我PropertySource在我的配置类上使用了注释:

@PropertySource("application-${spring.profiles.active}.yml")

@PropertySource("application-${spring.profiles.active}.yml")

spring.profiles.activereturns the active profile (dev, test, etc). My properties file name is application-dev.yml

spring.profiles.active返回活动配置文件(开发、测试等)。我的属性文件名是 application-dev.yml

The annotation @Scheduledworks with property injection. Dont forget the annotation with prefix configuration on your class.

该注释@Scheduled适用于属性注入。不要忘记类上带有前缀配置的注释。