***
### Dependencies
To get started with [[Caffeine Cache | Caffeine]] and Spring Boot, we first add the _[spring-boot-starter-cache](https://search.maven.org/artifact/org.springframework.boot/spring-boot-starter-cache)_ and [_caffeine_](https://search.maven.org/artifact/com.github.ben-manes.caffeine/caffeine) dependencies:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
```
### Auto-Configuration
**We need to enable caching in Spring Boot using the _@EnableCaching_ annotation**. This can be added to any _@Configuration_ class in the application or in your main Spring boot application class.
If Caffeine is present, a `CaffeineCacheManager` (provided by the `spring-boot-starter-cache` “Starter”) is autoconfigured. Caches can be created on startup by setting the `spring.cache.cache-names` property and can be customized by one of the following (in the indicated order): ^dbe8da
1. A cache spec defined by `spring.cache.caffeine.spec`
2. A `com.github.benmanes.caffeine.cache.CaffeineSpec` bean is defined
3. A `com.github.benmanes.caffeine.cache.Caffeine` bean is defined
For instance, the following configuration creates `cache1` and `cache2` caches with a maximum size of 500 and a _time to live_ of 10 minutes:
```properties
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
```
### Manual Configuration
First, we create a _Caffeine_ bean. **This is the main configuration that will control caching behavior such as expiration, cache size limits, and more**
```java
@Bean
public Caffeine caffeineConfig() {
return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);
}
```
Next, we need to create another bean using the Spring _CacheManager_ interface. Caffeine provides its implementation of this interface, which requires the _Caffeine_ object we created above:
```java
@Bean
public CacheManager cacheManager(Caffeine caffeine) {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.setCaffeine(caffeine);
return caffeineCacheManager;
}
```
> [!INFO] Multiple cache configurations problem
> ![[Multiple cache specifications in Spring with Caffeine#^ab1966]]
> Find the solution to this problem [[Multiple cache specifications in Spring with Caffeine#^315d0f | here]]
***
**References**:
- [Spring Boot and Caffeine Cache](https://www.baeldung.com/spring-boot-caffeine-cache)
- [Spring Boot OI](https://docs.spring.io/spring-boot/docs/current/reference/html/io.html#io.caching.provider.caffeine)