【问题标题】:How to map cache to a list of DTO object?如何将缓存映射到 DTO 对象列表?
【发布时间】:2022-10-22 09:11:02
【问题描述】:

我有这个缓存,它基本上是一个 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.

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

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

【问题讨论】:

    标签: java caching modelmapper


    【解决方案1】:

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

    您应该尝试另一种获取缓存类型的方法,也许cache.getClass() 或类似的东西可以解决问题。

    【讨论】:

    • 我是缓存的新手,缓存后缓存在运行时会改变它的类吗?所以这里在运行时 cache.getClass() 会返回 List<MyObjectDTO>?
    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多