javascript
Spring@Cacheable注解在类内部调用失效的问题
如圖所示,getRecomendGoogs方法里面調用findImgUrlByName方法,在findImgUrlByName方法上使用@Cacheable注解的時候,并沒有走緩存。
要解決這個問題,首先我們需要了解spring緩存的原理。spring cache的實現原理跟spring的事務管理類似,都是基于AOP的動態代理實現的:即都在方法調用前后去獲取方法的名稱、參數、返回值,然后根據方法名稱、參數生成緩存的key(自定義的key例外),進行緩存。debug可以看到調用的實際上是groupUserBiz的代理類,基于cglib動態代理實現。當調用代理的方法時,代理可以整體控制實際的方法的入參和返回值。比如緩存結果,直接跳過執行實際的方法等。?
找到了原因之后,我們有兩種解決方案
第一種:
把findImgUrlByName這個方法單獨寫到另外的一個類里面去,把類內部調用改成類之間調用
第二種:
使用內部調用的時候,自己實例化一個類對象,讓類走AOP,
寫一個工具類
@Component public class SpringContextUtil implements ApplicationContextAware {// Spring應用上下文環境private static ApplicationContext applicationContext;/*** 實現ApplicationContextAware接口的回調方法,設置上下文環境*?* @param applicationContext*/public void setApplicationContext(ApplicationContext applicationContext) {SpringContextUtil.applicationContext = applicationContext;}/*** @return ApplicationContext*/public static ApplicationContext getApplicationContext() {return applicationContext;}/*** 獲取對象*?* @param name* @return Object* @throws BeansException*/public static Object getBean(String name) throws BeansException {return applicationContext.getBean(name);}/*** 通過類型獲取對象*?* @param t* ? ? ? ? ? ?對象類型* @return* @throws BeansException*/public static <T> T getBean(Class<T> t) throws BeansException {return applicationContext.getBean(t);} }在getRecomendGoogs方法調用findImgUrlByName的時候使用
WeCommonService weCommonService = SpringContextUtil.getBean(WeCommonService.class);自己實例化service
?
---------------------?
作者:總有刁明想害朕?
來源:CSDN?
原文:https://blog.csdn.net/Crystalqy/article/details/83541054?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
總結
以上是生活随笔為你收集整理的Spring@Cacheable注解在类内部调用失效的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个故事讲清楚 NIO
- 下一篇: 经典面试题 | 讲一讲JVM的组成