问题描述
@Cacheable @Cacheevict 无效
我有这样的服务:
@service
pubic class TestService {
@Cacheable(cacheNames ="user",key = "#userId")
public User fetchUserById(Long userid) {
return new User();
}
public User fetchCurrentUser() {
return fetchUserById(124L);
}
}
有点问题:
@Cacheable
是有效的,当我调用 fetchUserById(Long userid)
时。
但是当我调用 @Cacheable
时 fetchCurrentUser()
无效。
解决方法
您可以在这里找到解决方案:Spring cache @Cacheable method ignored when called from within the same class
这是因为创建代理来处理缓存的方式, Spring 中与事务相关的功能。这是一个非常好的 Spring 如何处理它的参考 - 事务、缓存和 AOP: 了解 Spring 中的代理使用
简而言之,自我调用绕过了动态代理和任何横切 关注缓存、事务等,这是动态的一部分 代理逻辑也被绕过。
修复方法是使用 AspectJ 编译时或加载时编织。