问题
Considering a service class that can insert and retrieve objects and use Spring cache abstraction, how can I annotate methods in a way that an Optional is returned?
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) {
...
}
}
In the above example, a ClassCastException
is thrown because insertItem
puts an Item
instance in the cache, and findById
expects an Optional
that may contain an Item
instance.
回答1:
Just a follow-up on the comment to give a definitive answer to this one. We do as of Spring Framework 4.3 RC2
来源:https://stackoverflow.com/questions/36844270/handling-java-8-optional-with-spring-cache