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

在开发中,有时候我们需要为生产环境、测试环境、开发环境分别准备三个配置文件,那么我们怎样让系统启动时自动的去加载各自的配置文件,而不用手动的修改。
在介绍解决方法前,先简要描述下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");
	}
...

猜你喜欢

转载自461006791.iteye.com/blog/2208983