基于上下文路径的外部配置

Kei*_*ith 4 spring tomcat

我想在不同的上下文路径下在同一个tomcat服务器上部署特定Web应用程序的多个独立副本.每个Web应用程序都需要不同的配置设置(数据库名称,密码等),但我希望保持战争完全相同.

我的计划是让应用程序在启动时找出其上下文路径,然后读取由上下文路径标识的tomcat之外的特定.properties文件.例如,如果将战争部署到{tomcat path}/webapps/pineapple,那么我想读取/config/pineapple.properties

我一直试图通过spring(3)找到一种注入ServletContext实例的方法,但到目前为止我看到的所有建议都使用了弃用的ServletContextFactoryBean.

是否有更好的方法来注入上下文路径或更好的方法来加载基于上下文路径的外部文件?

小智 5

ServletContextAttributeFactoryBeanSpring EL 的帮助下,您可以<context-param>像这样引用ServletContext init参数(在web.xml中):

#{contextAttributes.myKey}
Run Code Online (Sandbox Code Playgroud)

这允许您PropertyPlaceHolderConfigurer从任意的,用户定义的位置使用和加载属性文件:

<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="#{contextParameters.APP_HOME}/conf/app.properties"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

Tomcat的context.xml中ServletContext init参数的相应定义:

<Parameter name="APP_HOME" value="file:/test" override="false"/>
Run Code Online (Sandbox Code Playgroud)

或者在你的应用程序的web.xml中:

<context-param>
    <param-name>APP_HOME</param-name>
    <param-value>file:/test</param-value>
</context-param> 
Run Code Online (Sandbox Code Playgroud)