Search code examples
javaxmlspringspring-el

Access application properties within SpEL in Spring xml configuration


I'm trying to configure a spring bean based on an application property, my end goal is described in the following pseudo code:

if ${my.config}
    <bean id="myBean" class="path.to.MyBeanImplOne" />
else
    <bean id="myBean" class="path.to.MyBeanImplTwo" />
end

where my.config is a boolean property. According to this SpEL guide, #{${my.config} ? 'path.to.MyBeanImplOne' : 'path.to.MyBeanImplTwo'} is a valid expression, so I tried the following configuration:

<bean id="myBean" class="#{${my.config} ? 'path.to.MyBeanImplOne' : 'path.to.MyBeanImplTwo'}" />

but got the following exception:

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

I can't find documentation for accessing properties in SpEL expressions for xml configuration. Is this supported only in Java configuration?

I've seen a number of proposed solutions to my problem (some of which are in this question). I'd like to not use systemProperties since I feel this sort of configuration should not be specified a run arguments, and I feel the use of profiles is overkill for this particular use case.

Has someone been able to do what I've attempted successfully? Or can someone confirm whether or not the syntax I've tried to use is indeed not supported in xml configuration.


Solution

  • Try

    class="#{'${my.config}'.equals('true') ? 'path.to.MyBeanImplOne' : 'path.to.MyBeanImplTwo'}"
    

    EDIT

    This works for me...

    <bean id="foo" class="#{'${my.config}'.equals('true') ? 'java.lang.Integer' : 'java.lang.String'}">
        <constructor-arg value="1" />
    </bean>