Parameterizing Spring @Scheduled with default value
Asked Answered
M

1

10

I need to parameterize a @Scheduled method with value from my properties file if present, or default value if not.

We can parameterize from configuration file property in the following way:

@Scheduled(cron = "${my.task.cron-exec-expr}")
public void scheduledTask() {
    // do something
}

but if the property does not exist we'll have a runtime exception.

I've tried using a @ConfigurationProperties bean with default value, with no success:

@Component
@ConfigurationProperties(prefix = "my.task")
public class MyTaskProperties {

    private String cronExecExpr = "*/5 * * * * *";

    // getter and setter
}

How to avoid that and pass a default value?

Miche answered 31/8, 2016 at 11:21 Comment(0)
R
22

You can add the default value in the placeholder like this:

@Scheduled(cron = "${my.task.cron-exec-expr:*/5 * * * * *}")
Reforest answered 31/8, 2016 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.