0

I want to create a custom spring @Cachable annotation, where i can defined the expire time in seconds. The problem is, i don't know how i implement the new method "expiresInSec()" in the custom annotation.

Here is my custom @Cachable annotation:

@Retention(RetentionPolicy.RUNTIME) @Target( {ElementType.TYPE, ElementType.METHOD}) public @interface Cachable { Cacheable cachable(); // cache entry expires in 1 hour by default int expiresInSec() default 3600; } 

This is the call of custom annotation:

@Cachable(cachable = @Cacheable("WorkListRepository::getWorkList"), expiresInSec = 60) 

But the expireInSec parameter doesn't work. Where i must implementing this parameter method.

Thank you

1 Answer 1

1

Extending the Spring Cacheable would require more than just adding extra attributes in the annotation. You need to extends the capabilities of annotation processor for caching in Spring as well. Check here for more details on what it would take.

Spring caching is an abstraction and requires a cache provider and generally the expiry is set on the cache level ( for e.g, Ehcache has timeToLiveSeconds parameter for each cache)

Sign up to request clarification or add additional context in comments.

4 Comments

If i use Ehcache, then i must create a xml file for configuration of each cache. Is that correct?
And can i use Ehcache as well as spring cache? With the annotations?
You will have to use some provider. Spring boot checks the dependencies on classpath to automatically determine the provider. E.g. you may have mentioned Ehcache in your build file then Spring boot will at runtime check the provider jar. However by default Spring boot Ehcache integration will not get initilized until a configuration file ( by default ehcache.xml is not provided). Check here for an example with TTL with Ehcache and Spring boot. baeldung.com/spring-boot-ehcache
Yes i've found this page of baeldung too, but i must create a xml file for expiry of cache. I want to define the expiry of a cache over the @Cachable annotation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.