Spring 启动@Scheduled cron

Spring Boot @Scheduled cron

有没有办法从 Spring 的 @Scheduled cron 配置中的 属性 类调用 getter(甚至变量) ?以下不编译:

@Scheduled(cron = propertyClass.getCronProperty())@Scheduled(cron = variable)

我想避免直接抓取 属性:

@Scheduled(cron = "${cron.scheduling}")
@Component
public class MyReminder {

    @Autowired
    private SomeService someService;

    @Scheduled(cron = "${my.cron.expression}")
    public void excecute(){
        someService.someMethod();
    }
}

在/src/main/resources/application.properties

my.cron.expression = 0 30 9 * * ?

简答 - 开箱即用是不可能的。

@Scheduled 注释中作为 "cron expression" 传递的值在 ScheduledAnnotationBeanPostProcessor class 中使用 StringValueResolver 接口的实例进行处理。

StringValueResolver 有 3 个开箱即用的实现 - Placeholder(例如 ${}),Embedded 值和 Static 字符串 - none 其中可以实现您正在寻找的东西。

如果您必须不惜一切代价避免在注释中使用属性占位符,请删除注释并以编程方式构建所有内容。您可以使用 ScheduledTaskRegistrar 注册任务,这正是 @Scheduled 注释的实际作用。

我会建议使用任何能够工作并通过测试的最简单的解决方案。

如果您不想从 属性 文件中检索 cron 表达式,您可以按如下所示以编程方式执行此操作:

// Constructor
public YourClass(){
   Properties props = System.getProperties();
   props.put("cron.scheduling", "0 30 9 * * ?");
}

这允许您在不做任何更改的情况下使用您的代码:

@Scheduled(cron = "${cron.scheduling}")