版权声明:本文为博主原创文章,转载请注明原文地址。 https://blog.csdn.net/qq342643414/article/details/78033799
在开发的时候通常会碰到一下的场景:一个分支,在开发环境运行测试的时候连开发数据库(或者linux相关路劲配置),在本地运行测试
的时候连本地数据库(windows下相关路径测试),那么简单粗爆的方法就是同一个属性写几条不同个值,在相应的环境做对应的注释。
在spring3.1之后有了profile,可以一键开关式的快速的切换环境。
profile的主要配置
配置环境
在applicationContext.xml(spring下上文配置文件)中添加下边的内容,就可以了
<beans profile="develop">
<context:property-placeholder location="classpath*:jdbc-develop.properties"/>
</beans>
<beans profile="production">
<context:property-placeholder location="classpath*:jdbc-production.properties"/>
</beans>
<beans profile="test">
<context:property-placeholder location="classpath*:jdbc-test.properties"/>
</beans>
profile的定义一定要在文档的最下边,否则会有异常。整个xml的结构大概是这样的
<beans xmlns="..." ...>
<bean id="dataSource" ... />
<bean ... />
<beans profile="...">
<bean ...>
</beans>
</beans>
我通过给不同的环境,引入不同的properties来设置不同的属性,你也可以直接在bean里进行定义一些特殊的属性,比如下边这样,在test的时候,初始化数据库与默认数据。(代码摘录:springside)
<!-- unit test环境 -->
<beans profile="test">
<context:property-placeholder ignore-resource-not-found="true"
location="classpath*:/application.properties,
classpath*:/application.test.properties" />
<!-- Simple连接池 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 初始化数据表结构 与默认数据-->
<jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
<jdbc:script location="classpath:sql/h2/schema.sql" />
<jdbc:script location="classpath:data/import-data.sql" encoding="UTF-8"/>
</jdbc:initialize-database>
</beans>
切换环境
在web.xml中添加一个context-param来切换当前环境:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>develop</param-value>
</context-param>
如果是测试类可以使用注解来切换:
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@ActiveProfiles("test")
public class DictionaryServiceTest extends AbstractTransactionalJUnit4SpringContextTests
你可以写一个基类来写这个注解,然后让你们测试类都继承这个测试基类,会很方便。