Disable @Cacheable in Spring Boot
Last Updated :
18 Sep, 2024
Caching is an essential feature in modern web applications, providing faster access to frequently used data and reducing the load on databases. In Spring Boot, the @Cacheable
annotation is commonly used to cache method results. However, there may be scenarios where you need to disable caching for specific operations, such as during testing, debugging, or when handling sensitive data that should not be cached.
In this article, we will explore different ways to disable the @Cacheable
annotation in Spring Boot.
Spring Boot provides caching abstraction through annotations like @Cacheable
, @CachePut
, and @CacheEvict
. Disabling caching can be useful in scenarios like:
- Development or testing, where you want fresh data with each request.
- Handling dynamic data that should not be cached.
- Debugging specific flows without caching interference.
There are several methods to disable @Cacheable
, such as globally disabling caching, conditionally turning off caching, or using Spring Profiles to toggle caching.
Methods to Disable @Cacheable
1. Disabling Caching Globally
To disable caching across the entire application, you can remove or comment out the @EnableCaching
annotation in the main Spring Boot class.
@SpringBootApplication
// @EnableCaching // Disabling this will turn off caching globally
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. Disable @Cacheable
Conditionally
You can control caching based on specific conditions (such as environment, feature toggle, or runtime logic) using Spring Expression Language (SpEL) in the @Cacheable
annotation.
@Cacheable(value = "products", condition = "#disableCaching == false")
public List<Product> getProducts(boolean disableCaching) {
// Simulating a database call with a delay
System.out.println("Fetching products from database...");
return Arrays.asList(
new Product(1L, "Product A"),
new Product(2L, "Product B"),
new Product(3L, "Product C")
);
}
The @Cacheable
annotation caches the result of getProducts()
. The condition
parameter uses SpEL to control when caching occurs. Here, caching is disabled if disableCaching
is true
.
3. Disable Caching Based on Profiles
You can disable caching based on active Spring Profiles, allowing different caching behavior in different environments (e.g., development vs. production).
In the application-dev.properties
file, you can disable caching for the dev
profile.
# Disable caching in dev environment
spring.cache.type=none
In the method, you can specify that caching is disabled when the dev
profile is active.
@Profile("!dev") // Disable caching in the 'dev' profile
@Cacheable("users")
public User getUser(Long id) {
return userRepository.findById(id).orElse(null);
}
The @Profile
annotation specifies that this caching behavior will not apply when the dev
profile is active. When in the dev
environment, caching is disabled.
Project Implementation to Disable @Cacheable in Spring Boot
In this example project, we will create a simple Spring Boot application that demonstrates how to disable caching using the @Cacheable
annotation conditionally. We will structure the project to include:
- Caching service using the @Cacheble annotation.
- Controller to the access the service.
- Conditional caching based on the request parameters.
Step 1: Create a New Spring Boot Project
Using IntelliJ IDEA, create a new Spring Boot project with the following options:
- Name:
spring-boot-cache-disable-example
- Type: Maven
- Packaging: Jar
Click on the Next button.
Step 2: Add the Dependencies
Add the following dependencies into the Spring Boot project.
- Spring Web
- Lombok
- Spring Boot DevTools
- Spring Cache Abstraction
Click on the Create button.
Project Structure
After project creation done, the folder structure will look like the below image:
Step 3: Configure Application Properties
In the application.properties
file, add the following cache configuration:
spring.application.name=spring-boot-cache-disable-example
spring.cache.type=simple # Enable caching with default settings
Step 4: Create the Product Class
Product.java:
Java
package com.gfg.springbootcachedisableexample;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private Long id;
private String name;
}
This class represents a simple Product
entity with id
and name
. It uses Lombok annotations to reduce boilerplate code for constructors and getters/setters.
Step 5: Create the ProductService Class
ProductService.java:
Java
package com.gfg.springbootcachedisableexample;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class ProductService {
@Cacheable(value = "products", condition = "#disableCaching == false")
public List<Product> getProducts(boolean disableCaching) {
// Simulating a database call with a delay
System.out.println("Fetching products from database...");
return Arrays.asList(
new Product(1L, "Product A"),
new Product(2L, "Product B"),
new Product(3L, "Product C")
);
}
}
- The
@Cacheable
annotation is used to cache the result of the getProducts()
method. The condition
ensures caching is disabled if disableCaching
is true
. - The method simulates fetching products from the database by returning a list of products with a delay.
Step 6: Create the ProductController Class
ProductController.java:
Java
package com.gfg.springbootcachedisableexample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/products")
public List<Product> getProducts(@RequestParam(defaultValue = "false") boolean disableCaching) {
return productService.getProducts(disableCaching);
}
}
- This controller exposes a
/products
endpoint, allowing clients to fetch the list of products. - The
disableCaching
parameter allows clients to control whether caching should be enabled or disabled for each request.
Step 7: Main Class
This is the main class of the Spring Boot application. We can enable the caching using the @EnableCaching annotation.
Java
package com.gfg.springbootcachedisableexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching // Enabling caching globally
public class SpringBootCacheDisableExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCacheDisableExampleApplication.class, args);
}
}
pom.xml File:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-boot-cache-disable-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-cache-disable-example</name>
<description>spring-boot-cache-disable-example</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 8: Run the Application
Run the application using the following Maven command:
mvn spring-boot:run
Output:
Step 9: Testing the Application
Use Postman or a similar tool to test the application.
1. First request with caching enabled (disableCaching=false
):
GET http://localhost:8080/products?disableCaching=false
Output:
If you can observe the logs then it will print "Fetching products from database..." that means data can fetched from the database.
2. Second request with caching disabled (disableCaching=true)
GET http://localhost:8080/products?disableCaching=true
Output:
When caching is disabled (disableCaching=true), we should see the message every time you hit the /products endpoint:
This example project demonstrates how to disable the caching conditionally in the spring Boot application. By using the @Cacheble annotation along with the conditions or request parameters, we can control whether to use the cache based on the runtime decisions.
Similar Reads
Spring Boot - Caching Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which e
6 min read
Spring Boot - Cache Provider The Spring Framework provides support for transparently adding caching to an application. The Cache provider gives authorization to programmers to configure cache explicitly in an application. It incorporates various cache providers such as EhCache, Redis, Guava, Caffeine, etc. It keeps frequently a
6 min read
Spring Boot - EhCaching EhCache is an open-source and Java-based cache. It is used to boost performance. Its current version is 3. EhCache provides the implementation of the JSR-107 cache manager. Features of EhCache are given below: It is fast, lightweight, Flexible, and Scalable.It allows us to perform Serializable and O
5 min read
Spring Boot Gradle Plugin The Spring Boot Gradle plugin provides several Spring Boot-specific features to Gradle, a popular build tool for Java projects. It helps to build and manage the lifecycle of Spring Boot applications. The Spring Boot Gradle plugin enables us to build and manage our Spring Boot applications with the G
2 min read
Spring Boot - Caching with Redis Caching is a crucial optimization technique used to enhance the performance and scalability of web applications. It temporarily stores data in cache memory to reduce access time and load on backend systems. Redis (Remote Dictionary Server) is a popular open-source, in-memory data structure store use
7 min read