spring - SpEL 无法访问实例变量

标签 spring spring-el

我正在尝试利用 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/

相关文章:

java - 在 Spring 中编写自定义 PlaceholderResolver(如 PropertyPlaceholderConfigurerResolver)

java - 使用 SpEL 在 Spring 中引用当前 bean

spring - 如何在没有 itemwriter 的情况下编写 spring 批处理步骤

java - 查询挂起oracle 10g

spring-integration - 如何使用SPEL引用@GatewayHeader中参数的属性

java - 使用 boolean 字段的评估上下文进行 Spring 表达式解析

spring - 如何在 SpEL 中按类型引用 bean?

java - Spring JPA、Eclipselink 和审计

java - Struts 测试 JUnit4

java - 没有唯一索引字段的 SQL 更新字段