Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a custom Spring @Cacheable annotation

I'm currently writing a custom @Cacheable annotation that will take additonal meta-data attributes in addition to those that Spring's @Cacheable provides. However, Spring would need to know how to parse this new annotation. My understanding is that I'd need to extend and override AnnotationCacheOperationSource's determineCacheOperations() so that the new annotation can be parsed with an appropriate CacheableOperation class initialized from it. Is this the correct way to proceed?

Regards,

Steve

like image 909
SNK Avatar asked May 27 '26 05:05

SNK


1 Answers

Depends.

As per AnnotationCacheOperationSource javadoc,

This class reads Spring's Cacheable, CachePut and CacheEvict annotations and exposes corresponding caching operation definition to Spring's cache infrastructure. This class may also serve as base class for a custom CacheOperationSource.

So if you're asking for yes/no answer if you can extend that class for an extended behaviour of CacheOperationSource, the answer is yes.

However, what determineCacheOperations() method does is that it uses all the available CacheAnnotationParsers. The only default CacheAnnotationParser is SpringCacheAnnotationParser. If you have a custom one, just have another class implementing CacheAnnotationParser for your annotation. Spring should then use it automatically. You can take a look at the SpringCacheAnnotationParser source code to see how they do it.


Edit: ok, I was wrong in that this would happen automatically. My next suggestion is to

  • implement the interface CacheAnnotationParser, like you apparently already did
  • extend AnnotationCacheOperationSource so that you put your own CacheAnnotationParser in addition to Spring one in the internal parsers collection
  • define your custom AnnotationCacheOperationSource to use the same id as Spring one does, so it will override Spring internal. If id matches, it should override Spring one cleanly. This would be something like:

    <bean id="annotationCacheOperationSource" class="com.company.YourCustomAnnotationCacheOperationSource" />

like image 52
eis Avatar answered May 30 '26 04:05

eis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!