Java Spring缓存-@cacheexecute,@CachePut在从同一类的另一个方法调用时不工作

Java Spring缓存-@cacheexecute,@CachePut在从同一类的另一个方法调用时不工作,java,spring,caching,ehcache,Java,Spring,Caching,Ehcache,从同一类的另一个方法调用缓存的方法时,Spring缓存不工作 这里有一个例子来清楚地解释我的问题 缓存的服务类: class testServiceImpl{ @CachePut(key = "#result.id", condition = "#result != null") public List<String> create(String input) { ...... } @CacheEvict(key="#id&quo

从同一类的另一个方法调用缓存的方法时,Spring缓存不工作

这里有一个例子来清楚地解释我的问题

缓存的服务类:

class testServiceImpl{

@CachePut(key = "#result.id", condition = "#result != null")
public List<String> create(String input) {
......
}

@CacheEvict(key="#id")
public void deleteById(Long id) {
.....
}

public void multiDelete(String input) { 
if(condition...){
  deleteById(2);  //Cache is not Evicted here i.e. the records are still present in getAll call but not in Database.
}else{
  create(input); //New Data is persisted in DB but the same has not been updated in Cache.
}   

@Transactional
@Cacheable
public Map<Long, String> getAll() {
 ...
}

有人能帮我解决这个问题吗?

当你从服务中调用一个方法时,实际上是通过代理调用它。自动连线bean被包装在一个代理中,该代理拦截调用并仅处理该方法的缓存注释

在内部进行调用时,直接在服务对象上进行调用,如果没有代理包装器,则不会处理缓存注释。


一种可行的替代方法是使用它将处理缓存注释的spring特性直接编织到代码中,而不使用任何spring代理,这样您就可以调用内部方法,缓存注释将按预期处理。

您看过这个吗?@cdalxndr的答案是正确的。比使用AspectJ更好的解决方案是直接调用缓存。您可以通过启动
CacheManager
并调用
getCache(name)
来实现这一点,您可以举一个AspectJ的例子吗?我如何在这里使用AspectJ来解决这个问题?@AmitAgarwal我个人建议不要使用AspectJ,因为你可能会进入一个难以调试的世界。如果您觉得有冒险精神,基本上您需要使用
spring启动程序aop
,添加
spring方面
依赖项,设置
@EnableCaching(mode=AdviceMode.ASPECTJ)
,并为加载时编织添加VM选项
-javaagent:
//Create a new object of the same class and use the same. In this case, the data is not persisted in DB i.e. it is not deleting the data from DB.
     testServiceImpl testService;
                ...
              public void multiDelete(String input) {   
                if(condition...){
                  testService.deleteById(2);  
                }else{
              testService.create(input); 
            }