Spring Cache - @CacheEvict、@CachePut 在从同一类的另一个方法调用时不起作用

Ami*_*wal 4 java spring caching ehcache

当从同一个类的另一个方法调用缓存的方法时,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() {
 ...
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用以下解决方案,但未能成功。

//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); 
            }
Run Code Online (Sandbox Code Playgroud)

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

cda*_*ndr 5

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

当您在内部进行调用时,它是直接在服务对象上进行的,如果没有代理包装器,则不会处理缓存注释。 请参阅了解 AOP 代理

一个可行的替代方案是使用AspectJ,它将处理缓存注释的 Spring 方面直接编织到代码中,而不使用任何 Spring 代理,因此您可以调用内部方法,并且缓存注释将按预期进行处理。