相关疑难解决方法(0)

从同一个类中调用时,忽略Spring缓存@Cacheable方法

我正在尝试@Cacheable从同一个类中调用一个方法:

@Cacheable(value = "defaultCache", key = "#id")
public Person findPerson(int id) {
   return getSession().getPerson(id);
} 

public List<Person> findPersons(int[] ids) {
   List<Person> list = new ArrayList<Person>();
   for (int id : ids) {
      list.add(findPerson(id));
   }
   return list;
}
Run Code Online (Sandbox Code Playgroud)

并希望结果findPersons也被缓存,但@Cacheable注释被忽略,并且findPerson每次都执行方法.

我在这里做错了什么,或者这是有意的吗?

spring caching spring-cache

36
推荐指数
2
解决办法
2万
查看次数

在@PostConstruct期间使用@Cacheable的Spring缓存不起作用

与spring框架中的提交有关https://github.com/spring-projects/spring-framework/commit/5aefcc802ef05abc51bbfbeb4a78b3032ff9eee3

初始化设置为从afterPropertiesSet()afterSingletonsInstantiated()的后续阶段

简而言之:这可以防止在@PostConstruct用例中使用缓存时缓存工作.

更长的版本:这可以防止您使用的用例

  1. 在methodB上使用@Cacheable创建serviceB

  2. 使用@PostConstruct调用serviceB.methodB创建serviceA

    @Component 
    public class ServiceA{
    
    @Autowired
    private ServiceB serviceB;
    
    @PostConstruct
    public void init() {
        List<String> list = serviceB.loadSomething();
    }
    
    Run Code Online (Sandbox Code Playgroud)

这导致org.springframework.cache.interceptor.CacheAspectSupport现在不进行初始化,因此不会缓存结果.

protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
   // check whether aspect is enabled
   // to cope with cases where the AJ is pulled in automatically
   if (this.initialized) {
//>>>>>>>>>>>> NOT Being called
      Class<?> targetClass = getTargetClass(target);
      Collection<CacheOperation> operations = getCacheOperationSource().getCacheOperations(method, targetClass);
      if (!CollectionUtils.isEmpty(operations)) { …
Run Code Online (Sandbox Code Playgroud)

java postconstruct spring-cache

6
推荐指数
2
解决办法
3247
查看次数

标签 统计

spring-cache ×2

caching ×1

java ×1

postconstruct ×1

spring ×1