Spring @Cacheable注解类内部调用失效问题

如果你只是想使用一个轻量级的缓存方案,那么可以尝试使用Spring cache方案。

但是,在使用Spring @Cacheable注解的时候,要注意,如果类A的方法f()被标注了@Cacheable注解,那么当类A的其他方法,例如:f2(),去直接调用f()的时候,@Cacheable是不起作用的,原因是@Cacheable是基于Spring AOP代理类,f2()属于内部方法,直接调用f()时,是不走代理的。举个例子:

@Cacheable(key = "#entityType", value = "xxxCache")
public List<String selectByEntityType(intentityType) {
    List<String> result = new ArrayList<>();
    // do something

    return result;
}

public List<String> f2(){
    // Cacheable失效,不会走缓存的
    selectByEntityType(1);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可以把selectByEntityType方法抽取到另外的类中,例如:

@Service
public class CacheService {
    @Cacheable(key = "#entityType", value = "xxxCache")
    public List<String selectByEntityType(intentityType) {
        List<String> result = new ArrayList<>();
        // do something

        return result;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

这样其他类要使用selectByEntityType方法,只能注入CacheService,走代理。

转自:http://blog.csdn.net/linsongbin1/article/details/51304138

猜你喜欢

转载自blog.csdn.net/gangsijay888/article/details/80974476