多环境配置一直都是一件头疼不已的事情,spring自3.1以后引入Profile的方式实现多环境切换。下面我结合个人经验介绍一种简单的配置方式。
假设存在三种环境:
dev-开发环境;test-测试环境;pro-生产环境;
准备工作:
在工程的resources目录下分别创建开发环境配置文件config-dev.properties、测试环境配置文件config.test.properties和生产环境配置文件config-pro.properties。
1、配置web.xml
<!-- Context ConfigLocation --> <!-- dev:开发环境; pro:生产环境;test:测试环境; --> <context-param> <param-name>spring.profiles.active</param-name> <param-value>dev</param-value> </context-param>
2、在spring的applicationContext.xml文件中引入config-xxx.properties配置文件
<context:property-placeholder ignore-unresolvable="true" location="classpath*:config-${spring.profiles.active}.properties" />
3、在程序中取得profile的配置
1> 配置web.xml
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>com.lh.web.listener.WebContextListener</listener-class> </listener>
2>在WebContextListener中取得profile配置信息
package com.lh.web.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoaderListener;
public class WebContextListener extends ContextLoaderListener {
private static final Logger LOGGER = LoggerFactory.getLogger(WebContextListener.class);
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
String active = context.getInitParameter("spring.profiles.active");
if("dev".equals(active)){
LOGGER.info("开发环境");
}else if("test".equals(active)){
LOGGER.info("测试环境");
}else if("pro".equals(active)){
LOGGER.info("生产环境");
}else{
LOGGER.error("环境配置错误!");
}
}
}
参考网站:
1、http://www.jianshu.com/p/948c303b2253
2、http://vito16.com/2014/08/13/using-spring-profile-on-deploy.html
The end!