Issue
I am trying to create a bean for cacheManager only when a specific cachemanager is not configured.
@Bean
@ConditionalOnProperty(name = "spring.cache.type", matchIfMissing = true)
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {
@Override
protected Cache createConcurrentMapCache(final String name) {
return new ConcurrentMapCache(name,
CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build().asMap(), false);
}
};
return cacheManager;
}
This bean is created even when I have the property
spring.cache.type=redis
is configured. Did try different combinations with prefix with no luck. This bean is injected regardless of whether the cache type is specified or not in the application.properties.
Solution
The issue seems to be that the default value of having
attribute does not work as you expect it to. Reading the reference documentation you will find the following for having
:
The string representation of the expected value for the properties. If not specified, the property must not be equal to false.
This means, that in your case (because you are not specifying the value), the condition will always match unless you have spring.cache.type=false
. This is also shown in the reference documentation in the following table (the property value "foo" will actually match the condition if havingValue=""
which is actually the default if you do not specify it):
Having said all that I would say that your best option would be to create your own Condition
just like @ray suggested.
Answered By - João Dias
Answer Checked By - Mary Flores (JavaFixing Volunteer)