Search code examples
spring-bootkotlinenvironment-variablesspring-cachespring-profiles

Spring Boot - How to disable @Cacheable for spring.profiles.active = test?


I need to enable in_memory caching for a method only for spring.profiles.active = test. Only requests from the last 10 minutes need to be cached.

Now I set it up like this:

@Profile("test")
@Configuration
class CachingConfig {
    @Bean
    fun cacheManager() = Caffeine.newBuilder()
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build<Any, Any>()
}
@Cacheable("request", key = "#dto.id")
fun request(dto: RequestDTO): Any {
    ...
}
@EnableCaching
@SpringBootApplication
@EnableConfigurationProperties
class Application

fun main(args: Array<String>) {
    SpringApplication.run(Application::class.java, *args)
}

build.gragle

test {
    systemProperty "spring.profiles.active", "test"
}

But I'm afraid to expand it on because I'm not sure if it will work correctly there.

I don't fully understand: how would this work for spring.profiles.active = prod?

  1. Will there be an error when the cacheManager bean is not raised for prod?
  2. And will not a situation happen that on prod spring will raise the cacheManager by default?

Solution

  • You need to move @EnableCaching from class Application to class CachingConfig to make caching work only for Profile = "test"

    @Profile("test")
    @EnableCaching
    @Configuration
    class CachingConfig { ... }
    

    With this approach CachingConfig will not even be loaded into application context when non-"test" profiles are active