Will Spring's @CachePut annotation work with a void return type?

隐身守侯 提交于 2020-07-20 10:55:50

问题


I am attempting to implement caching in my application using Ehcache and the Spring 3.1 built in caching annotations (@Cacheable, @CacheEvict, and @CachePut).

I have created a cache as follows:

@Cacheable(value = "userCache", key = "#user.id")
public List<User> getAllUsers() {
...
}

I am attempting to update this cache with a new value using the @CachePut annotation as below:

@CachePut(value = "userCache", key = "#user.id")
public void addUser(User user) {
...
}

However, the new "User" is not being added to the cache. Is this because of the void return type?


回答1:


Yes, it's because void return type. The @CachePut annotation places the result of method into the cache. In your case there is no result so nothing is put to the cache.

Change method signature to return User:

public User addUser(User user) { 
   ...
}



回答2:


This wont work , cause you are using same cache value "userCache" but return type of method getAllUsers is List and return type of addUser is User. which will create inconsistency in data that have been stored in cache.

( List + User ) : this type of data will be formed in cache.

And later when you will call method getAllUsers , code will be

List userList = getAllUsers();

But in this case , data will be fetched from cache and throw "Class cast Exception".

As , ( List + User ) can not be cast in to List.

Is there any solution to this? I am stuck with this and don't know how to proceed. Will using custom annotations work here?



来源:https://stackoverflow.com/questions/17946426/will-springs-cacheput-annotation-work-with-a-void-return-type

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