Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Cacheable condition using application properties

Tags:

java

spring

I'm trying to use Redis with Spring's @Cacheable but need to conditionally turn caching on or off based on a Spring Boot style application property. My first attempt doesn't seem to work.

The application.properties file:

auth.token-cache-enabled=false

The properties class:

@Component
@ConfigurationProperties(prefix = "auth")
public class AuthProperties {
    public boolean tokenCacheEnabled;
    ...
}

The service method annotation:

@Cacheable(key = "#token", condition = "@authProperties.tokenCacheEnabled()")

Results in:

org.springframework.expression.spel.SpelEvaluationException: EL1057E:(pos 1): No bean resolver registered in the context to resolve access to bean 'authProperties' at org.springframework.expression.spel.ast.BeanReference.getValueInternal(BeanReference.java:48)

Does anyone have an idea what the problem is or if there's another way to achieve this?

like image 803
Tom Collins Avatar asked Sep 05 '25 18:09

Tom Collins


1 Answers

I found a way to make this work in my situation, but I also found a bug ticket for what I believe is the same issue: https://jira.spring.io/browse/SPR-13812

My workaround is to @Inject my AuthProperties in to the service containing the method I want to cache. Next, I changed the method's cache condition to this:

    @Cacheable(key = "#token", condition = "#root.target.authProperties.tokenCacheEnabled")
like image 96
Tom Collins Avatar answered Sep 08 '25 07:09

Tom Collins