I have to add handling of new version of external API for one of clients. So we had beans with @Component annotation had additional annotation:
@ConditionalOnProperty(name = SOME_PROPERTY_NAME, havingValue = "val1")
Thus in many cases I create new Components with condition “havingValue = ‘val2′”, but some beans do not require changes.
After search here and other places the only working solution I found is to use
@ConditionalOnExpression("'${some.property}' == 'val1' or '${some.property}' == 'val2'")
But I have found that it should be possible to register custom functions which would work in SpEL expression, which would be more neat, especially if condition will get more complicated.
What is the best solution to use in such scenario?
First I checked possibility to add logic to @ConditionalOnProperty, but after reading some answeres here moved to @ConditionalOnExpression.
Then I have tried to add
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction(...);
and finally I have registered BeanFactoryPostProcessor as in https://gist.github.com/thomasdarimont/7df3f04d3be7acea5dfa
with
public interface CustomSpelFunctions {
static boolean isIntegrationEnabled(@Value("${some.property}") String mode) {
return ...
}
}
but as far as I can see beans get created before I can register anything, when I try to use
@ConditionalOnExpression("#{isIntegrationEnabled()}")
I get errors like this or similar:
EL1004E: Method call: Method isIntegrationEnabled() cannot be found on type org.springframework.beans.factory.config.BeanExpressionContext
What I am doing wrong? Is it possible to use custom function there? Or the only solution is to type condition directly in @ConditionalOnExpression annotation
I moved from non-spring to spring java quite recently and this is new for me.
We are using spring-boot-starter-parent 2.4.13
Zeb is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.