Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of annotation processing in Spring (@Cacheable and @Timed)

I want to annotate my method with @Cacheable and also with @Timed (from micrometer). But I would like the @Timed to be applied only in case when the data is not timed. Is there a way to do that, is it enough to put the annotations in correct order - and which order would that be?

My @Timed is also using TimedAspect, not sure if that is relevant.

Right now I do it like below:

@Cacheable
@Timed
public String getValue(long id) {
    ...
}

I couldn't find any documentation for @Cacheable that would discuss this.

like image 826
Krzysztof Krasoń Avatar asked Nov 06 '22 12:11

Krzysztof Krasoń


1 Answers

This is tricky, since you are dealing with AOP proxies created by Spring around your business bean, so I am not sure whether you can rely on the order of the annotations.

I think that you have several options:

  • You might want to refactor your code to have several methods, one marked with @Cacheable and the other with @Timed. However, I think that this will not work with you since you need more than one bean (calls whitin the same bean are not intercepted by the AOP proxies). Therefore, you would need two beans, one acting as facade and the other doing the actual @Timed expensive call that you want to cache and monitor.
  • Another option might be to extend both @Timed and @Cacheable and implement Orderable in both interfaces, then use them in your bean. I am not totally sure that this will work, as it will depend on how the annotations are picked up. Something along this line: Specifying the order of proxy creation in Spring

Hope it helps.

like image 110
Victor Avatar answered Nov 12 '22 17:11

Victor