What is a right Spring Cache Configuration for Java Map and its values?

Viewed 13135

I have next service that returns the whole map and a value by a key.

@Service
@CacheConfig(cacheNames = "messages")
public class MessageService {

    private final MessageRepository messageRepository;

    @Autowired
    public MessageService(MessageRepository messageRepository) {
        this.messageRepository = messageRepository;
    }

    @Cacheable
    public Map<String, String> findMessages() {
        return messageRepository.findAll();
    }

    @Cacheable(key = "#key")
    public String getMessage(String key) {
        return messageRepository.findByKey(key);
    }
}

When findMessages() method will be invoked I want to save all the messages in cache. And when getMessage(String key) will be invoked it should return a value from the cache, but not from the repository. Is it possible to do it using Spring annotations? Currently it have separate cache entries for both of the methods.

2 Answers
Related