Access application properties within SpEL in Spring xml configuration

走远了吗. 提交于 2019-12-11 01:38:28

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/46235311/access-application-properties-within-spel-in-spring-xml-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!