【问题标题】:Access application properties within SpEL in Spring xml configuration在 Spring xml 配置中访问 SpEL 中的应用程序属性
【发布时间】:2017-09-15 08:41:49
【问题描述】:

我正在尝试基于应用程序属性配置一个 spring bean,我的最终目标在以下伪代码中描述:

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

其中my.config 是一个布尔属性。 根据this SpEL 指南,#{${my.config} ? 'path.to.MyBeanImplOne' : 'path.to.MyBeanImplTwo'} 是一个有效的表达式,所以我尝试了以下配置:

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

但出现以下异常:

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({)'

我找不到用于访问用于 xml 配置的 SpEL 表达式中的属性的文档。是否仅在 Java 配置中支持?

我已经看到了许多针对我的问题提出的解决方案(其中一些在这个question 中)。我不想使用systemProperties,因为我觉得这种配置不应该被指定为运行参数,而且我觉得profiles 的使用对于这个特定的用例来说太过分了。

有人能够成功地完成我尝试过的事情吗?或者有人可以确认xml配置中是否确实不支持我尝试使用的语法。

【问题讨论】:

    标签: java xml spring spring-el


    【解决方案1】:

    试试

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

    编辑

    这对我有用...

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

    【讨论】:

    • 我也试过了,但我遇到了一个异常,因为它无法将字符串转换为布尔值,这意味着它没有提取属性,而是将其视为字符串。
    • 但我收到了错误 Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [#{'true'.equals('true') ? 'java.lang.Integer' : 'java.lang.String'}] for bean with name 'foo' defined in class path resource [spring/command-context.xml]; nested exception is java.lang.ClassNotFoundException: #{'true'.equals('true') ? 'java.lang.Integer' : 'java.lang.String'} 。春季版本 3.2.3.RELEASE 。这里有什么问题?
    • 不要在 cmets 中就旧答案提出新问题。提出一个新问题并提供更多信息,包括您的配置。 Spring 3.2.x 不再受支持,因此您应该升级到更新的版本。
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2014-04-23
    • 2015-03-22
    • 2022-09-25
    • 2020-06-30
    相关资源
    最近更新 更多