s1m*_*r3d 2 java scheduled-tasks spring-scheduled
我需要@Scheduled使用属性文件中的值(如果存在)或默认值(如果不存在)对方法进行参数化。
我们可以通过以下方式从配置文件属性中进行参数化:
@Scheduled(cron = "${my.task.cron-exec-expr}")
public void scheduledTask() {
// do something
}
Run Code Online (Sandbox Code Playgroud)
但是如果该属性不存在,我们将有一个运行时异常。
我尝试使用@ConfigurationProperties具有默认值的bean,但没有成功:
@Component
@ConfigurationProperties(prefix = "my.task")
public class MyTaskProperties {
private String cronExecExpr = "*/5 * * * * *";
// getter and setter
}
Run Code Online (Sandbox Code Playgroud)
如何避免这种情况并传递默认值?
您可以像这样在占位符中添加默认值:
@Scheduled(cron = "${my.task.cron-exec-expr:*/5 * * * * *}")
Run Code Online (Sandbox Code Playgroud)