0

How to pass the annotation attribute. I wanted to add my variable String(ans) in the Cron annotation but i am getting exception can you please suggest me how can i do it.

I wanted to get the corn pattern from the database and store it to the ans variable which is creating issue.

    @Service
public class CronService {
    
    @Autowired
    UserDao userdao;
    
    String ans="* * * * * *";
    
    @Scheduled(cron="{ans}")
    public void add() {
        System.out.println("Hello");
    }

}

1 Answers1

1

Annotation values has to be known at compilation time, i.e. you can't set them dynamically. But in Spring you can use EL expressions to circumvent this, so the value will come from configuration instead. For example see Chapter 8 here: https://www.baeldung.com/spring-scheduled-tasks

In this particular case you could use

@Scheduled(cron="${my.cron.expression}")

then you should set the property value in XML.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63