Spring Boot - How to disable @Cachable during deve

2019-01-23 04:59发布

问题:

I'm looking for 2 things:

  1. How to disable all caching during development with Spring boot "dev" profile. There doesn't seam to be a general setting to turn it all off in application.properties. What's the easiest way?

  2. How to disable caching for a specific method? I tried to use SpEl like this:

    @Cacheable(value = "complex-calc", condition = "#{${spring.profiles.active} != 'dev'}") public String someBigCalculation(String input){ ... }

But I can get it to work. There are a couple of questions on SO related to this, but they refer to XML config or other things, but I'm using Spring Boot 1.3.3 and this uses auto-configuration.

I don't want to over-complicate things.

回答1:

The type of cache is by default automatically detected and configured. However you can specify which cache type to use by adding spring.cache.type to your configuration. To disable it set the value to NONE.

As you want to do it for a specific profile add it to that profiles application.properties in this case modify the application-dev.properties and add

spring.cache.type=NONE

This will disable caching.



回答2:

For your second question do something like this:

Write a method that determines whether or not a particular profile is active (environment is your injected Environment)

boolean isProfileActive(String profile) { 
   return Arrays.asList(environment.getActiveProfiles()).contains(profile);
}

then use that for your spel condition on the cacheable annotation