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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more