比如:UserService 类的某个方法create()调用了 findById(Long id) 方法,并且findById(Long id) 方法用了spring的缓存。
如果直接用this,或者直接调用,缓存就会失效。这时候可以在UserService内使用 ((UserService)AopContext.currentProxy()) 获取当前类的代理,强制转换为当前类。使用方式如下:
- 配置
expose-proxy="true"。
<aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true" />
2、使用代理。代码类型下面。
public class UserServiceImpl implements UserService {
public void create(){
//使用代理
((UserService)AopContext.currentProxy()).findById(1110);
}
@Cacheable(cacheNames=, key="#某个key", unless="#result == null")
public User findById(Long id){
return User
}
}
参考文档: https://blog.youkuaiyun.com/weixin_35796363/article/details/86306291
Spring缓存失效问题及解决
本文探讨了在Spring框架中,当UserService类的create()方法调用findById(Long id)时,若直接使用this或直接调用,可能导致缓存失效的问题。通过配置expose-proxy=true并使用AopContext.currentProxy()方法,可以正确利用代理,确保缓存机制正常工作。
1470

被折叠的 条评论
为什么被折叠?



