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

问题描述

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

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

//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); 
            }

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

解决方法

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

在内部进行调用时,将直接在服务对象上进行调用,并且在没有代理包装的情况下,不处理缓存注释。 See Understanding AOP Proxies

一种可行的选择是使用AspectJ,它将无需处理任何Spring代理即可将处理缓存注释的spring方面直接编织到代码中,因此您可以调用内部方法,缓存注释将按预期进行处理。 / p>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...