Using the Grails Cache Plugin Annotation on Normal Groovy Classes

494 Views Asked by At

Is it possible to use the Grails Cache plugin's annotations (ie: @Cacheable) on methods in normal Groovy classes? The plugin's documentation doesn't mention anything about normal Groovy classes and based on my own tests the annotations have no effect when used in a normal class. So I'm just wondering if there's a way to get the annotations to work in a normal Groovy class.

The current alternative is to simply directly access the cache in the method via the Cache Manager bean, but it would be nice to use the annotations instead.

1

There are 1 best solutions below

0
On

No, the annotation only works on services and controllers. The plugin detects the annotation and creates a proxy for the service which intercepts all method calls and does the cache-related work first. So if there is a value in the cache for that method, it won't bother calling your real method but return the cached value instead. But if it's not cached, it will call your method and use its return value, but cache that for later.

This works because you have to retrieve the service from the Spring ApplicationContext (or have Grails do that for you) and this gives Spring a chance to give you the proxy instead of the real implementation instance, but there's no way for Spring to know about access to regular Groovy classes without AOP or some other more invasive solution.

Having said that, the plugin is probably being overly strict in limiting to only controllers and services. It handles controllers specially because those involve caching web requests instead of method return values, but there shouldn't be much difference between a Grails service and any other annotated Spring bean as far as caching goes. You can add your own Spring beans, either manually in grails-app/conf/spring/resources.groovy or by adding them to the grails.spring.bean.packages list in Config.groovy, so the plugin should be updated to look for all annotated classes. You can request this in the plugin's JIRA at https://jira.grails.org/browse/GPCACHE