0

The following custom configuration properties exist in my Spring Boot (2.5.4) application:

application.yml

app:
  tasks:
    - name: A
      url: http://server-a
      cron-expression: "*/5 * * * * *"
    - name: B
      url: http://server-b
      cron-expression: "*/10 * * * * *"

Configuration class

@Configuration
@ConfigurationProperties(prefix = "app")
@Getter
@Setter
public class ApplicationConfiguration {

    private List<TaskEntry> tasks;

    @Getter
    @Setter
    public static class TaskEntry {
        private String name;
        private String url;
        private String cronExpression;
    }
}

Now, there is also a method which shall run with the @Scheduled annotation. While specifying a variable expression for the cron argument is easy, I'm looking for a more dynamic apporach.

This cron-expression to be used in the @Scheduled annotation shall be selected by the TaskEntry with name == A. So I came up with something like this:

@Scheduled(cron = "${app.tasks.?[name == 'A'].cron-expression}")
public void run() {
    log.info("Starting task A...");
}

This fails with the following message:

Could not resolve placeholder 'app.tasks.?[name == 'A'].cron-expression' in value "${app.tasks.?[name == 'A'].cron-expression}"

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192
  • 2
    Probably easiest to turn the list into a map with `A`, `B`, ... as keys and `url` and `cronExpression` in a custom class as values. Then you can use `app.tasks.A.cron-expression`. – Henning Aug 19 '21 at 21:19
  • 2
    Agreed; also `${...}` is for simple property placeholders; to use SpEL, you need to use `#{...}` (and quote any properties within the SpEL - e.g. `cron = "#{'${app.tasks.A.partial-cron-expression}' + ' *'}"`). – Gary Russell Aug 19 '21 at 21:33
  • Thanks @Henning, guess I'll follow this approach. – Robert Strauch Aug 19 '21 at 21:42

0 Answers0