DEV Community

eidher
eidher

Posted on • Edited on

1

Caching in Spring

When you have a method that always returns the same result for the same arguments (calculations, queries, requests, etc.), you can implement caching. You just need to mark the method as cacheable:

@Cacheable("books")
public Book findBook(String refId) {...}
Enter fullscreen mode Exit fullscreen mode

Its result is stored in a cache and the subsequent invocations (with the same arguments) will fetch the data from the cache using the key, and the method will not be executed.

The @Cacheable annotation has two main attributes, the value (name of the cache) and the key (for each cached data-item). In the previous example, we used a default key. Let's see an example with a custom key, where we can use SpEL (see Spring Expression Language) and arguments of method:

@Cacheable(value="books", key="#refId.toUpperCase()")
public Book findBook(String refId) {...}

// Only cache if condition is true
@Cacheable(value="books", key="#title", condition="#title.length < 10")
public Book findBook(String title, boolean checkWarehouse) {...}

// Using an object property
@Cacheable(value="books", key="#isbn.rawNumber")
public Book findBook(ISBN isbn, boolean checkWarehouse) {...}
Enter fullscreen mode Exit fullscreen mode

Caching must be enabled using the @EnableCaching annotation in the configuration class (see Spring Configuration)

See https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/integration.html#cache

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay