DEV Community

eidher
eidher

Posted on • Updated on

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

Top comments (0)