用 Spring 区分开发环境、测试环境、生产环境
我们在项目开发过程中,经常需要往开发环境、测试环境、生产环境部署程序。随着程序越来越复杂,配置文件的增多,如果每次部署都去改一遍配置文件,这种重复的工作会把程序员逼疯。
好在spring提供了这一自动切换的功能,简要说明如下:
- 首先在applicationContext中,对需要配置的参数进行配置,以下图为例:
<bean id="minaService" class="com.***.***.mina.MinaService"
scope="singleton" lazy-init="false" init-method="init" destroy-method="destroy">
<property name="port" value="${port}" />
<property name="bothIdleTime" value="${both_idle_time}" />
<property name="protocolCodecFilter" ref="protocolCodecFilter" />
<property name="poolSize" value="${pool_size}" />
</bean>
-
再准备好开发环境配置文件config.local.properties,测试环境文件config.test.properties,以下示例:
1)开发环境:
port=8888 both_idle_time=120 pool_size=16
2)测试环境:
port=6666 both_idle_time=120 pool_size=16
-
在spring applicationContext.xml中,配置如下参数:
<beans profile="local">
<context:property-placeholder
ignore-resource-not-found="true" location="classpath:/config/config.local.properties" />
</beans>
<beans profile="test">
<context:property-placeholder
ignore-resource-not-found="true" location="classpath:/config/config.test.properties" />
</beans>
| Column 1 | Column 2 | Column 3 |
| -------- | -------- | -------- |
| Text | Text | Text |
-
在web.xml中,配置如下参数:
<context-param> <param-name>spring.profiles.default</param-name> <param-value>local</param-value> </context-param>
-
按以上4步配置完毕后,就可以开发、测试、生产各配置一套配置文件了。第4步中的配置,是指默认加载local配置文件。我们在实际使用过程中,肯定是希望在哪个环境下就自动加载哪个环境的配置,那么该如何做呢?我们来看第6步
-
我们可以在服务器(如weblogic)的启动脚本中增加一个参数,例如EVN,然后再指定Active的环境是EVN,示例如下:
export ENV=test export JAVA_OPTIONS="-Dspring.profiles.active=${ENV}”
至此,大功告成。
本作品采用《CC 协议》,转载必须注明作者和本文链接