Handling Java 8 Optional with Spring cache

心不动则不痛 提交于 2020-01-14 08:58:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!