项目开发中切换部署开发、测试、生产多环境

在开发的过程当中,不可避免会接触到至少三个环境的程序部署:开发、测试和生产环境。web

每一个环境都使用一套数据库配置,路径配置等,若是每次都人工的干预每个配置文件,工做会比较繁杂,且容易遗漏而且出错。spring

spring3.1以后提供了profile功能,能够切换不一样的自定义profile环境,惟一的缺点是和maven结合不大好,只能在web.xml中进行修改。数据库

方法以下:oracle

一、在beans.xml中定义各个环境。maven

<beans profile="develop">
</beans>
<beans profile="test">
</beans>
<beans profile="product">
</beans>

每一个环境若是使用了不一样的配置文件(properties文件等)能够在环境中进行加载声明。测试

该段代码需在文件根节点的最后一段url

spa

<beans profile="test">  
    <context:property-placeholder location="classpath*:jdbc-test.properties"/>  
</beans> 

二、定义属性以外的配置,如指定数据库bean等code

<beans profile="test,develop">
    <bean id="authDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
        </property>
        <property name="url"
            value="jdbc:oracle:thin:@208.120.102.10:1522:ora11g">
        </property>
        <property name="username" value="user"></property>
        <property name="password" value="passwd"></property>
    </bean>
</beans>
<beans profile="product">
    <bean id="authDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
        </property>
        <property name="url"
            value="jdbc:oracle:thin:@198.121.33.7:1521:ora10g">
        </property>
        <property name="username" value="user"></property>
        <property name="password" value="passwd"></property>
    </bean>
</beans>

此处定义了不一样环境下不一样的数据库连接信息xml

三、web.xml中定义当前使用哪一个环境

在web.xml中操做context-param节点

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>product</param-value>
</context-param>

部署时指定哪一个环境为激活状态便可。

若是进行junit测试可使用

@ActiveProfiles({"test","develop"}) 

 

附: 若是spring的profile能够和maven的发布共同做用就更好了,可是笔者目前还未能成功将2者结合。

配置提醒:

<beans xmlns="http://www.springframework.org/schema/beans" profile="test,develop" -----设置这个以后,数据库只对test,develop有效xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- 定义数据链接池 --> <!-- 使用spring自带的DriverManagerDataSource方式 -->

相关文章
相关标签/搜索