---
title: "Spring3自定义环境配置 <beans profile=\"\">"
author: "wusuoya"
date: "2015-04-22T10:51:22Z"
tags: ["Spring", "profile"]
categories: ["企业架构"]
slug: "spring3-beans-profile"
draft: false
lastmod: "2015-04-22T11:05:54Z"
id: 2204960
url: "https://canann.iteye.com/blog/2204960"
---

摘自springside3 

Spring 3.1的功能，以后就不用为了区分Test, Dev, Production环境，搞几个只有细微区别的application.xml, application-test.xml及引用它们的web.xml了。

首先，将applicationContext.xml中的namespace从3.0升级到3.1.xsd， 然后就可以在文件末尾加入不同环境的定义，比如不同的dataSource

Xml代码  [![收藏代码](http://nassir.iteye.com/images/icon_star.png)]()

1. &lt;beans profile="test"&gt;
2. &lt;jdbc:embedded-database id="dataSource"&gt;
3. &lt;jdbc:script location="classpath:com/bank/config/sql/schema.sql"/&gt;
4. &lt;/jdbc:embedded-database&gt;
5. &lt;/beans&gt;
6. &lt;beans profile="production"&gt;
7. &lt;jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/&gt;
8. &lt;/beans&gt;

   
2.在web.xml里，你需要定义使用的profile，最聪明的做法是定义成context-param，注意这里定义的是default值，在非生产环境，可以用系统变量"spring.profiles.active"进行覆盖。

Xml代码  [![收藏代码](http://nassir.iteye.com/images/icon_star.png)]()

1. &lt;context-param&gt;
2. &lt;param-name&gt;spring.profiles.default&lt;/param-name&gt;
3. &lt;param-value&gt;production&lt;/param-value&gt;
4. &lt;/context-param&gt;

   
3.在其他地方进行覆盖

3.1 在development和functional test启动Jetty前设置系统变量

Java代码  [![收藏代码](http://nassir.iteye.com/images/icon_star.png)]()

1. System.setProperty("spring.profiles.active", "development");
2. server.start()

   
3.2 在用到ApplicationContext的单元测试用例中，用 @ActiveProfiles定义

Java代码  [![收藏代码](http://nassir.iteye.com/images/icon_star.png)]()

1. @ContextConfiguration(locations = { "/applicationContext.xml" })
2. @ActiveProfiles("test")
3. public class AccountDaoTest extends SpringTxTestCase {
4. }

   
在springside里有演示了production,development，test,functional三个环境， 大家可以根据实际情况组合自己的环境管理。另外可以与Spring的properties文件加载时可顺位覆盖的特性(放一些不在版本管理中的xx.local.properties文件)，更好的支持本地开发环境，Jenkins上的functional test等其他环境。

 

详情：[https://github.com/springside/springside4/wiki/Spring](https://github.com/springside/springside4/wiki/Spring)

http://jinnianshilongnian.iteye.com/blog/2000183

 

详细配置与使用：[http://www.cnblogs.com/chanedi/archive/2012/01/12/2320837.html](http://www.cnblogs.com/chanedi/archive/2012/01/12/2320837.html)