tomcat 中java web 项目的生产环境、测试环境、开发环境配置文件管理

本文介绍了在开发、测试和生产环境中,如何管理Java Web项目的配置文件,通过修改Tomcat的web.xml及Spring配置,实现不同环境加载对应的properties文件。详细步骤包括设置spring.profiles.active参数,定义不同环境的bean,以及在项目中读取配置信息的方法。
在开发中,有时候我们需要为生产环境、测试环境、开发环境分别准备三个配置文件,那么我们怎样让系统启动时自动的去加载各自的配置文件,而不用手动的修改。
在介绍解决方法前,先简要描述下tomcat 启动后加载文件的顺序(可跳过一,直接看二)

一、Tomcat的class加载的优先顺序一览
1.最先是$JAVA_HOME/jre/lib/ext/下的jar文件。

2.环境变量CLASSPATH中的jar和class文件。

3.$CATALINA_HOME/common/classes下的class文件。

4.$CATALINA_HOME/commons/endorsed下的jar文件。

5.$CATALINA_HOME/commons/i18n下的jar文件。

6.$CATALINA_HOME/common/lib 下的jar文件。

(JDBC驱动之类的jar文件可以放在这里,这样就可以避免在server.xml配置好数据源却出现找不到JDBC Driver的情况。)

7.$CATALINA_HOME/server/classes下的class文件。

8.$CATALINA_HOME/server/lib/下的jar文件。

9.$CATALINA_BASE/shared/classes 下的class文件。

10.$CATALINA_BASE/shared/lib下的jar文件。

11.各自具体的webapp /WEB-INF/classes下的class文件。

12.各自具体的webapp /WEB-INF/lib下的jar文件

二、实现上面的要求,我们需要修改这几个文件,
1、tomcat的bin目录下的web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>test</param-value>
</context-param>

2、在spring的配置文件中添加多个benans
<beans profile="development">
<context:property-placeholder ignore-resource-not- found="true"location="classpath*:/application_development.properties"/>
</beans>
<beans profile="test">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/application_test.properties" />
</beans>

<beans profile="production">
<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/application_production.properties" />
</beans>
三、如果在项目中需要读取配置文件中得信息,需要以下几处调整
1、spring容器启动监听类
在项目的web.xml中注册个监听类。在此类中写入
		if (ToolUtils.isNotEmpty(evt.getServletContext().getInitParameter("spring.profiles.active"))){
//将当期文件名放入内存
System.setProperty("profilesName", evt.getServletContext().getInitParameter("spring.profiles.active"));
logger.info(evt.getServletContext().getInitParameter("spring.profiles.active"));

}else{
//将当期文件名放入内存
System.setProperty("profilesName", evt.getServletContext().getInitParameter("spring.profiles.default"));
logger.info(evt.getServletContext().getInitParameter("spring.profiles.default"));

}

2、配置文件读取类
代码片段
public class ResourceUtil  {

private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("application_"+System.getProperty("profilesName"));

/**
* 获得sessionInfo名字
*
* @return
*/
public static final String getSessionInfoName() {
return bundle.getString("sessionInfoName");
}
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值