@ConditionalOnExpression with #{systemEnvironment}

Viewed 669

I am trying to setup a @ConditionalExpression with the use of environment variables as follows:

@ConditionalOnExpression("#{systemEnvironment['PUBLIC']?:'false'} != true")

I can see this is evaluated within following code:

    private Boolean evaluateExpression(ConfigurableListableBeanFactory beanFactory, String expression) {
        BeanExpressionResolver resolver = beanFactory.getBeanExpressionResolver();
        if (resolver == null) {
            resolver = new StandardBeanExpressionResolver();
        }
        BeanExpressionContext expressionContext = new BeanExpressionContext(beanFactory, null);
        Object result = resolver.evaluate(expression, expressionContext);
        return (result != null && (boolean) result);
    }

The problem is that the resolver.evaluate(expression, expressionContext); returns false != true where this should already be a boolean:

return (result != null && (boolean) result);

So this always fails with ClassCastException.

I tried also to fiddle with different kind of quoting and wrapping it whole with ${…}, but always with the same result.

Question is: What is wrong with my conditional expression?

1 Answers

One solution could be this expression:

@ConditionalOnExpression("#{!(systemEnvironment['PUBLIC']?:'false').equals('true')}")

Need to add that if this question is not for investigation purpose but for finding the way to improve your real (production-like) code, I'd really recommend you to:

  1. always try to simplify that kind of expression because it really hard to understand what's really happening when you see a lot of boolean comparisons, default values, etc;
  2. use spring-boot specific things more:
    1. when you're working with boolean expressions, you can usually replace @ConditionalOnExpression with @ConditionalOnProperty (optionally with matchIfMissing parameter);
    2. when you need to read environment variables, you can use relaxed binding feature instead of using things from (mostly) the pre-Spring-Boot era like systemProperties/systemEnvironment.
Related