5

I created an abstract class like this:

abstract class ScheduledProcess {

  abstract List<String> fetchNewContent()
  abstract List<String> cron()

  //This SPeL doesn't work just stating what kind of expression I'm looking for
  @Scheduled(cron='#{this.cron()}')
  void persistContent(){
     doSomeStuffWithContent(fetchNewContent())
  }

}

My goal is to do not repeat myself having to implement the @Scheduled method in all subclasses. The cron() method returns the specific subclass cron expression. However I'm not finding a way to pass to the annotation the cron value. Maybe I'm just looking at this problem the wrong way.

rsilva4
  • 1,915
  • 1
  • 23
  • 39

2 Answers2

2

I think this is now possible (Spring 4.3.0) you can see it in the issue.

https://jira.spring.io/browse/SPR-13625

If you are using another Spring version you can write your own beanpostprocessor. You can see an example in the answer given by quantum here

Injecting externalized value into Spring annotation

Community
  • 1
  • 1
reos
  • 8,766
  • 6
  • 28
  • 34
  • `@Scheduled(cron='#{this.cron()}')` is this supported in spring boot ? I am having similar problem – Shettyh Jan 12 '20 at 05:16
0

You can't use SpEL there, only property placeholders ${...}.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • Can you elaborate on the why isn't possible to use SpEL? Is a @Scheduled annotation specific restriction? Using property placeholders do you have an idea how can I achieve what I want? – rsilva4 Jul 13 '16 at 15:32
  • 1
    Simply that the `ScheduledAnnotationBeanPostProcessor` has no logic to evaluate a SpEL expression. Such logic would need to be added, with the current bean as the `#root` evaluation object (or otherwise made available as a SpEL variable such as `#currentBean`). No, it can't be done using placeholders. You could write your own bean post processor and use it instead of the standard one; but it requires a good understanding of Spring internals and SpEL. – Gary Russell Jul 13 '16 at 16:07