This question is possibly a duplicate of this older question.
I'm working on a Spring Boot 1.4 application and I have a method of a bean annotated with @Scheduled
.
I need to pass the cron value to the annotation and, since I'm using YAML based configuration, the cron value is stored in the YAML file (application.yaml
).
I can't find a way to pass the property value app.cron
to the annotation.
For instance, this doesn't work
@Scheduled(cron = ${app.cron})
I have also tried to use EL expression, but no luck.
What is the proper way to pass a YAML based property value to a Spring annotation?
Try putting it in a Javaconfig first and it should work with EL:
@Configuration
@ConfigurationProperties(prefix = "app")
public class CronConfig {
private String cron;
@Bean
public String cron() {
return this.cron;
}
public void setCron(String cron) {
this.cron = cron;
}
}
And use it with @Scheduled(cron = "#{@cron}")
I didn't tried this for scheduled Taks but I had similar problem with injecting something to an annotation.
You can also do this:
@Configuration
public class CronConfig() {
@Value("${app.cron}")
private String cronValue;
@Bean
public String cronBean() {
return this.cronValue;
}
}
And use it with @Scheduled(cron = "#{@cronBean}")
In this case you'll get the value of "app.cron" from Spring's application.properties or application.yml, the one that you've configured in your project.
Note:
There is a little mistake in the code posted by Dennis:
The method cron() is calling itself:
@Bean
public String cron() {
return this.cron(); // It's calling itself
}
So if you run this code you will get and StackOverFlow Exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With