Spring SpEL usage issue: calling child instance method in SpEL expression at @Scheduled annotation not working

Viewed 403

I have multiple cron tasks which run at different intervals and all of them have some common tasks which i wanted to perform at super class (abstract) and provided couple of abstract methods which need to be implemented by child classes. Out of these methods, getCronExpr , is one method which must be implemented by child class and return respective cron expression. This is what i'm doing to achieve this:

public abstract class AbstractTask{
   @Scheduled(cron="#{@this.getCronExpr()}")
   public void run(){
     System.out.println("cron execution started");
   }
   public abstract String getCronExpr();
}

@Component
@EnableScheduling
@EnableAsync
public MyTask1 extends AbstractTask{
@Override
public String getCronExpr() {
    logger.info("inside getCronExpr method");
    return "0 0/2 * * * ?";
}
}

@Component
@EnableScheduling
@EnableAsync
public MyTask2 extends AbstractTask{
@Override
public String getCronExpr() {
    logger.info("inside getCronExpr method");
    return "0 0/60 * * * ?";
}
}

But this, @Scheduled(cron="#{@this.getCronExpr()}"), is giving me below error

org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1058E: A problem occurred when trying to resolve bean 'this':'Could not resolve bean reference against BeanFactory'

Instead of using this, if i refer exact bean id, its working fine, like this: @Scheduled(cron="#{@myTask1.getCronExpr()}")

But i cannot do like this becoz there are multiple child classes and this cron expression need to evaluated corresponding to the child instance. Since yesterday, i searched all over internet and tried all possible ways, but none of them are working.

For your information, i'm using below spring jars:

spring-core-4.3.10.RELEASE.jar
spring-osgi-core-1.2.1.jar
spring-expression-4.3.10.RELEASE.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-aop-4.3.10.RELEASE.jar
spring-data-mongodb-1.9.7.RELEASE.jar
spring-data-commons-1.12.6.RELEASE.jar
spring-tx-4.3.10.RELEASE.jar
spring-web-4.3.10.RELEASE.jar
0 Answers
Related