Spring之项目中pofile的应用

    工程中,咱们必需要面对的一件事就是, 开发环境中使用的数据库链接地址等与生产上的不一样, 若是上线, 那么咱们是否还要手动修改这些地址么, 这样作有不少弊端, 不方便, 这时咱们就能够使用spring的profile来解决.java

1 修改web.xml

    在web.xml中加入以下List-1.1的内容.web

    List-1.1spring

<context-param>
    <param-name>spring.profiles.default</param-name>
    <!--生产环境时,改成production,开发时改成development-->
    <param-value>development</param-value>
</context-param>

2 resources下的properties文件

    以下图2.1所示, development下放置的是开发时使用的配置; production下是生产上使用的配置.数据库

                                                       

                                                                                           图2.1app

    以后在spring的xml配置中,以下List-2.1所示, 重点是profile的值分别是development和production, 像List-1.1中那样使用的就是开发环境的.单元测试

    List-2.1测试

<beans profile="development">
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:properties/development/db.properties</value>
                <value>classpath:properties/development/application.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="UTF-8"/>
    </bean>
</beans>
<beans profile="production">
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:properties/production/db.properties</value>
                <value>classpath:properties/production/application.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="UTF-8"/>
    </bean>
</beans>

3 单元测试时如何配置

    单元测试时, 建一个TestBase类, 加上注解@ActiveProfiles, 值是development, 以后全部的单元测试类都继承它, 就能够了. spa

    List-3.13d

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring-context.xml"})
@ActiveProfiles("development")
public class TestBase {

}

                                                                                               

    这样作了以后, 咱们上线须要将List-1.1中的值改成production就能够了.code

相关文章
相关标签/搜索