How @CachePut Updates Cache in Spring Cache
The article explains that @CachePut serves as a trigger to update or add cache entries in Spring Cache, contrasting its behavior with @Cacheable, detailing execution flow, handling of null results, and the recommendation against using both annotations on the same method.
Function Description
When using cache in daily development we not only need to add or delete entries but also update them. In Spring Cache the @CachePut annotation enables cache updates. @CachePut can be thought of as a trigger: each time the annotated method is invoked, the trigger runs and either clears the specified key's cache or updates it.
Different Logic Based on Return Value
If the method returns null, a subsequent query for the same key will miss the cache and the database will be queried again, which is equivalent to the behavior of @CacheEvict.
If the method returns a non‑null value, the cache entry for that key is updated with the returned data.
Differences Between @CachePut and @Cacheable
@CachePutis responsible for adding or updating cache entries. @Cacheable is responsible for reading cache entries; if a cache miss occurs, the method executes and its result is stored in the cache, otherwise the cached data is returned directly. @Cacheable is suitable for methods that query data, while @CachePut is suitable for methods that modify data.
The official documentation strongly advises against applying both @Cacheable and @CachePut to the same method.
The explanation of @CachePut ends here; readers are invited to leave comments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
