【问题标题】:Resolving system environment variable using Spring Expression Language使用 Spring 表达式语言解析系统环境变量
【发布时间】:2014-05-27 22:26:27
【问题描述】:

我想在 spring servlet 配置文件中使用“Spring Expression Language”解析系统环境变量。我的第一个方法是:

 <bean id="propertyConfigurer"
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
     p:location="/WEB-INF/jdbc.#{systemEnvironment.THREAD_ENV}.properties" />

这是抛出异常:

Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 18): Field or property 'THREAD_ENV' cannot be found on object of type 'java.util.Collections$UnmodifiableMap'

那我试过了:

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.#{systemEnvironment['THREAD_ENV']}.properties" />

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.#{systemEnvironment[THREAD_ENV]}.properties" />

都失败并解析为空字符串。我正在使用 Tomcat6,并在重新启动 Tomcat 服务器之前导出此变量:

export THREAD_ENV=live;
/etc/init.d/tomcat6 restart;

想提一下,这三种方法都适用于我的一些 Tomcat6 实例,但并非全部适用——这种奇怪行为的原因是什么?知道我做错了什么吗?

【问题讨论】:

    标签: spring environment-variables spring-el


    【解决方案1】:

    SpEL 变量是systemProperties,而不是systemEnvironment

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.#{systemProperties['THREAD_ENV']}.properties" />
    

    【讨论】:

    • 这是否适用于操作系统系统变量?我希望它只适用于 jvm 属性 - 无论如何我已经尝试过了,我的变量再次解析为空字符串。
    • Spring 同时提供systemPropertiessystemEnvironment
    • @SotiriosDelimanolis 你在哪里找到的?我能找到的唯一参考是Spring API 的倾斜参考,我假设(但它不是明确的)与 SpEL 相关,并说“systemEnvironment”来自操作系统,“systemProperties”来自 JVM。我的简短测试证实了后者,但我无法使用 systemEnvironment 获取 Windows 环境变量。
    • @SotiriosDelimanolis 找到了它 - 它在 Spring API entry for PropertySourcesPlaceHolderConfigurer 中,我无意中使用了过时的普通 ol' PropertyPlaceholderConfigurer。不得不将架构参考升级到 spring-context-3.1.xsd 并将 propertyConfigurer 类升级到 org.springframework.context.support.PropertySourcesPlaceholderConfigurer 并且突然它起作用了。在“SpEL”上搜索的时间太长了
    • @Adam 也可以看看StandardEnvironment。它是大多数Environment 类型的基类。
    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2013-06-14
    相关资源
    最近更新 更多