【发布时间】:2016-08-19 01:29:45
【问题描述】:
考虑到可以插入和检索对象并使用 Spring 缓存抽象的服务类,我如何以返回 Optional 的方式注释方法?
class MyServiceImpl implements MyService {
private static final String CACHE_NAME = "itemCache";
@Override
@Cacheable(CACHE_NAME)
public Optional<Item> findById(Long id) {
// access the repository to retrieve the item
}
@Override
@CachePut(cacheNames = CACHE_NAME, key = "#item.id")
public Item insertItem(Item item) {
...
}
}
在上面的示例中,ClassCastException 被抛出,因为insertItem 将Item 实例放入缓存中,而findById 期望Optional 可能包含Item 实例。
【问题讨论】:
-
我们还不支持
Optional。我想我们可以这样做,请创建一个问题。 -
感谢您的回复。我刚刚创建了jira.spring.io/browse/SPR-14230
-
哇,我现在正在度假,而 Juergen 已经实现了它。那很快;-)
标签: java spring spring-cache