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

2022-07-02 14:26:55

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

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

@Cacheable(key="#entityType", value="xxxCache")publicList<String selectByEntityType(intentityType) {List<String> result=new ArrayList<>();// do somethingreturn result;
}publicList<String> f2(){// Cacheable失效,不会走缓存的
    selectByEntityType(1);
}

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

@Servicepublicclass CacheService {
    @Cacheable(key ="#entityType",value ="xxxCache")public List<StringselectByEntityType(intentityType) {
        List<String> result =new ArrayList<>();// do somethingreturn result;
    }
}

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

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

  • 作者:totally123
  • 原文链接:https://blog.csdn.net/totally123/article/details/56284711
    更新时间:2022-07-02 14:26:55