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.

Coder Trainee
Coder Trainee
Coder Trainee
How @CachePut Updates Cache in Spring Cache

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

@CachePut

is 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaCacheSpring@Cacheable@CachePut
Coder Trainee
Written by

Coder Trainee

Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.