Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a YAML-based property value to @Scheduled annotation in Spring Boot

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?

like image 873
Luciano Avatar asked Sep 22 '16 14:09

Luciano


2 Answers

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.

like image 94
Dennis Ich Avatar answered Oct 02 '22 04:10

Dennis Ich


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.

like image 23
Carlos Zegarra Avatar answered Oct 02 '22 04:10

Carlos Zegarra