Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Java 8 Optional with Spring cache

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.

like image 897
andrucz Avatar asked Aug 04 '26 07:08

andrucz


1 Answers

Just a follow-up on the comment to give a definitive answer to this one. We do as of Spring Framework 4.3 RC2

like image 79
Stephane Nicoll Avatar answered Aug 05 '26 23:08

Stephane Nicoll