我正在尝试利用 Spring Boot AutoConfigured @EnableScheduling
创建一个 cron 作业。如果 fixedRateString
是硬编码的,作业触发完全正常。但是,如果我尝试使用 SpEL 来提供该值,则不会成功。
//Bean Instantiation in JavaConfig
@Bean
public AlertbotJob2 getAlertJob2() {
AlertbotJob2 alertbotJob2 = new AlertbotJob2("alertId", "alertName", "alertSubject", "6000", true);
return alertbotJob2;
}
Bean Definition
public class AlertbotJob2 {
String alertId;
String alertName;
String alertSubject;
public String cronPattern;
boolean isActive;
public AlertbotJob2() {
}
public AlertbotJob2(String alertId, String alertName, String alertSubject, String cronPattern, boolean isActive) {
super();
this.alertId = alertId;
this.alertName = alertName;
this.alertSubject = alertSubject;
this.cronPattern = cronPattern;
this.isActive = isActive;
}
@Scheduled(initialDelay = 60000, fixedRateString = "#{this.cronPattern}")
public void doTheJob() {
System.out.println("DoSomething");
}
}
Exception is :: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'this' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
我只是想动态设置触发值。请帮忙。
最佳答案
我认为你不能这样使用 SpEL。 也许更好的方法是在某些属性中定义您的 cron 模式,例如:
myapp.scheduler.cronPattern=...
然后使用以下语法:
@Scheduled(cron = "${myapp.scheduler.cronPattern}")
public void doTheJob() {
...
}
关于spring - SpEL 无法访问实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47875826/