从Spring Boot application.yml文件中注入@Scheduled fixedRate值

时间:2014-12-12 14:24:22

标签: spring spring-boot

我知道我可以使用以下语法从属性文件中注入值:

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

但是,如果配置在YAML文件中,我无法猜测如何完成相同的操作。

提前致谢,

3 个答案:

答案 0 :(得分:33)

在我的application.properties(YAML)中我把这个

console:
    fetchMetrics: 5000

哪个与Java配置类绑定

@Component
@ConfigurationProperties(prefix = "console")
public class ConsoleConfig {
    private long fetchMetrics;
    ...
}

然后在我简单的Task类中推送定义:

@Scheduled(fixedRateString ="${console.fetchMetrics}", initialDelay=1000)
public void fetchMetrics() {
    logger.info("What's up ?");
}

请注意,fixedRate期望long并且您想要注入占位符,您需要fixedRateString

答案 1 :(得分:9)

我觉得我的项目很容易完成。
postgresql.conf更改为fixedRate并将属性键放在fixedRateString中,如下所示:

double quotes

答案 2 :(得分:0)

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

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

spring.profiles.active返回活动配置文件(dev,test等)。我的属性文件名是application-dev.yml

注释@Scheduled适用于属性注入。 不要忘记你班上的前缀配置注释。

相关问题