使用spring profile实现多环境切换的简单实现

本文介绍了一种使用Spring Profile进行多环境配置的方法。通过在不同环境下加载对应的配置文件(如config-dev.properties、config-test.properties、config-pro.properties),实现了开发、测试及生产环境的灵活切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

多环境配置一直都是一件头疼不已的事情,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!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值