如何将缓存映射到DTO对象的列表



我有这个缓存,它基本上是DTO:的列表

A类:

@Cacheable("MyList")
public List<MyObjectDTO> setCachedList(){
return api.getList(); //call to another api to fetch that list
}

B类:

public List<MyObjectDTO> getCachedList(){
if(!CacheManager.getCacheNames().contains("MyList"){
ClassB.setCachedList();
}
Cache cache = CacheManager.getCache("MyList");
Type listType = new TypeToken<List<MyObjectDTO>>(){}.getType(); //error occurs here
List<MyObjectDTO> returnList = modelMapper.map(cache, listType);
return returnList;

我在上面的代码中得到以下错误:

Failed to instantiate instance of destination java.util.List. Ensure that java.util.List has a non-private no-argument constructor.

我看到了一个类似的问题,但由于我使用的是列表的缓存,所以我无法将其扩展到具体的类。

我不认为错误在您提到的行中,而是在后面的行中。类型返回List,但List是一个接口,因此无法实例化,映射程序必须捕获此异常并抛出错误。

您应该尝试另一种获取缓存类型的方法,也许cache.getClass()或类似的方法就可以了。

我能够通过在modelMapper中传递cache.get(SimpleKey.EMPTY).get()而不是缓存来解决这个问题。

最新更新