问题
I have upgraded my application to Spring 3.1 and all the jars have been adequately updated. But when I try to use @Cacheable for a method in one of my controllers, URL mapping for all the methods of that controller breaks. On checking the log files I found that the URL mapping for all the methods of that controller were never detected. I am pretty sure that my cache configurations are fine. Can anyone give me some clue as what I might be doing wrong.
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<defaultCache
eternal="false"
maxElementsInMemory="2"
overflowToDisk="false"
diskPersistent="false"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
<cache name="Backlog"
eternal="false"
maxElementsInMemory="2"
overflowToDisk="false"
diskPersistent="false"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
configuration:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<ref bean="ehcache" />
</property>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="/WEB-INF/spring-configuration/ehcache.xml" />
code snippet:
@RequestMapping("/*/backlog")
@Cacheable(value = "Backlog")
public ModelAndView getBackLog(){
//sth here
}
Thanks for the help.
回答1:
Whilst @mana has explained how to fix this, this is why adding @Cacheable breaks your code. A recent blog post explains this in more detail and is well worth a read.
By default Spring creates JDK dynamic proxies to achieve the caching behaviour, this requires that the class being proxied implements an interface which declares all the methods you wish to expose on your @Cacheable class. It is worth noting that you don't have to implement any interfaces if you configure Spring to use CGLIB based proxies.
You haven't supplied any specific errors but often you get a method not found exception in this scenario. Spring tries to invoke the getBackLog() method on the proxy and there isn't one.
回答2:
You shouldn't cache the controller method itself but the resource hungry method that will be called to create the backlog. Have a look at this similar question. What @Cachable does is to create a key value map for your function parameters and the related return value. In your case this would be a ModelAndView object.
If you really need server side web page caching maybe use this Apache Cache Module.
回答3:
you should be injecting your service class into the controller and caching the methods on the service class
来源:https://stackoverflow.com/questions/11187853/spring-cacheable-is-breaking-requestmapping