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 ,因为insertItem将Item实例放入缓存中,并findById期望Optional可能包含Item实例.
| 归档时间: |
|
| 查看次数: |
3045 次 |
| 最近记录: |