使用Spring缓存处理Java 8可选

and*_*ucz 6 java spring spring-cache

考虑一个可以插入和检索对象并使用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) {
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,ClassCastException抛出了a ,因为insertItemItem实例放入缓存中,并findById期望Optional可能包含Item实例.

Ste*_*oll 7

只需对评论进行跟进即可给出明确答案.我们从Spring Framework 4.3 RC2开始