如何使用 Tomcat 覆盖 spring 属性参数? [英] How to override spring property param with Tomcat?
问题描述
我已经在 Spring
应用程序中定义了属性.
I have defined property in Spring
application.
@Configuration
public class WebappConfiguration {
@Value("${ext.storage.path}")
private String extDirectoryPath;
public String getExtDirectoryPath() {
return extDirectoryPath;
}
}
ext.storage.path
属性的默认值在 application.properties
文件中定义.
Default value for ext.storage.path
property is defined in application.properties
file.
application.properties
ext.storage.path=/home/user/ext/
当我使用 VM 选项 -Dext.storage.path=/var/webapp-data/
将 WAR
部署到 tomcat 时,此值已成功加载.但我想从每个环境的上下文文件中更智能地加载属性值.
When I deploy WAR
to tomcat with VM options -Dext.storage.path=/var/webapp-data/
, this value is loaded successfully. But I would like to load property values more smarter from context files for every environment.
所以我把WAR
部署到Tomcat的ROOT
,WAR文件的名字是ROOT.war
,然后分解成ROOT
目录.我在路径 {CATALINA_BASE}/Catalina/localhost/ROOT.xml
上创建了 context
文件,内容如下.
So I deploy the WAR
to ROOT
of Tomcat, name of WAR file is ROOT.war
and it is exploded to ROOT
directory. I created context
file on path {CATALINA_BASE}/Catalina/localhost/ROOT.xml
with following content.
ROOT.xml
<Context
docBase="/opt/webapp-tomcat/webapps/ROOT.war"
path=""
reloadable="true">
<Parameter name="ext.storage.path" value="file:/var/webapp-data/" override="true"/>
</Context>
不幸的是,参数没有按照方式加载,它具有来自application.properties
的默认值.
Unfortunately, the param is not loaded according to the way, it has default value from application.properties
.
经过一番调查,我将Parameter
放入Tomcat的主context.xml
文件中,并覆盖了该值.
After a little investigation, I put the Parameter
into main context.xml
file of Tomcat and the value is overridden.
<Parameter name="ext.storage.path" value="file:/var/webapp-data/" override="true"/>
推荐答案
我所知道的最好的技术是将特定于环境的内容放入 Tomcat 的 conf/context.xml 文件中.
The best technique I know of is to put environment-specific stuff into Tomcat's conf/context.xml file.
<Environment name="myApp/extStoragePath" type="java.lang.String" value="/var/data/myapp"/>
这定义了一个 JNDI 变量,您可以使用以下内容在代码中查找该变量:
This defines a JNDI variable that you lookup in your code with something like this:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
String extStoragePath = (String) envCtx.lookup("myApp/extStoragePath");
您也可以使用这种技术来加载复杂的对象,如数据库数据源等.它具有巨大的优势:
You can also use this technique to load complex objects like database datasources etc. It has huge advantages:
- 配置是针对环境的,而不是针对应用程序的
- 您无需弄乱 Tomcat 启动脚本
- 相同的二进制文件无需修改即可在 DEV、UAT 和 PROD 中运行.这大大简化了构建过程.
此外,Spring 提供了一个 org.springframework.jndi.JndiObjectFactoryBean
,它可以从您的 Spring 配置文件访问 JNDI.
Also, Spring provides a org.springframework.jndi.JndiObjectFactoryBean
which can access JNDI from your spring configuration files.
这篇关于如何使用 Tomcat 覆盖 spring 属性参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!