如何在PropertyPlaceholderConfigurer中获取tomcat环境变量

Ric*_*old 4 java spring hibernate

我尝试server.xml在我的jpa-spring.xml文件中的'PropertyPlaceholderConfigurer' 中获取Tomcat 中指定的Environment变量.

到目前为止,设置如下:

Tomcat的 server.xml

<Environment description="Identifies the server environement" 
             name="server-env" 
             type="java.lang.String" 
             value="dev" />
Run Code Online (Sandbox Code Playgroud)

WebContent/META-INF/context.xml:

<Context>
    <ResourceLink name="server-env" global="server-env" type="java.lang.String"/>
</Context>
Run Code Online (Sandbox Code Playgroud)

哪个引用WebContent/WEB-INF/web.xml如下:

<resource-env-ref>
    <description>Identifies server environement</description>
    <resource-env-ref-name>server-env</resource-env-ref-name>
    <resource-env-ref-type>java.lang.String</resource-env-ref-type>
</resource-env-ref>

<!-- Spring Integration -->

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/config/jpa-spring.xml
</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

/WEB-INF/config/jpa-spring.xml我尝试将该变量作为替代品:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>WEB-INF/config/db.${server-env}.properties</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

这是我使用网上发现的几篇文章中的信息整理的设置.

但是,我得到一个像......的错误

Could not resolve placeholder 'server-env' in [WEB-INF/config/db.${server-env}.properties] as system property: neither system property nor environment variable found
05 Nov 2011 14:45:13,385 org.springframework.web.context.ContextLoader
ERROR Context initialization failed

org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/db.${server-env}.properties]
Run Code Online (Sandbox Code Playgroud)

...当启动tomcat时.

实现我正在寻找的东西的正确方法是什么?

我知道,这个问题类似于,和这个问题.但是,我甚至无法用这些答案中的信息弄明白.

San*_*osh 5

这是我的建议

  • 使用当前设置,读取JNDI属性server-env并使用相同的方法来加载属性文件真的很复杂.
  • 你组装spring应用程序(和PropertyPlaceholderConfigurer)的方式,spring将首先尝试server-env在OS环境中查找属性,然后在java系统属性中查找属性(使用-D选项从命令传递).它在这两个地方都找不到它,因此失败了.
  • 因此,目前最简单的方法是传递应用程序服务器的server-env form命令提示符的值(调用java的地方;典型的语法是-Dserver-env = dev).我把它留给你弄清楚.
  • 如果上面的选项看起来有点复杂,另一个更简单的方法是将名称为server-env的环境变量设置为适当的值(在Windows上set server-env=dev.Plz检查尊重OS文档).