gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:48:43 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

ServletContextAttributeFactoryBean的帮助下和 Spring EL,您可以像这样引用 ServletContext 初始化参数(web.xml 中的 <context-param>):

#{contextAttributes.myKey}

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

<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="#{contextParameters.APP_HOME}/conf/app.properties"/>
</bean>

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

<Parameter name="APP_HOME" value="file:/test" override="false"/>

或者在您应用的 web.xml 中:

<context-param>
<param-name>APP_HOME</param-name>
<param-value>file:/test</param-value>
</context-param>

关于spring - 基于上下文路径的外部配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4221974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com