软件开发过程一般有三个阶段:开发 > 测试 > 生产。每个阶段都对应不同的数据库环境配置,我们希望通过一种自动切换的方式来减少手动切换的工作量,这样做的目的也是为了能够减少手工带来的出错率。
spring 自带的profile很好的解决了这个问题,通过对配置文件的修改就能够达到自动切换的目的。
具体配置步骤如下:
1.在resource目录下建立每种环境对应的文件夹,用来存放配置文件。
development文件夹 : 存放 dev.properties
production文件夹 : 存放 produce.properties
test 文件夹: 存放 test.properties
2. spring -mybatis.xml(spring的配置文件) 中设置profile。
<!-- 开发环境配置文件 --> <beans profile="development"> <context:property-placeholder location="classpath:development/*.properties" /> </beans> <!-- 测试环境配置文件 --> <beans profile="test"> <context:property-placeholder location="classpath:test/*.properties" /> </beans> <!-- 生产环境配置文件 --> <beans profile="production"> <context:property-placeholder location=" classpath:production/*.properties" /> </beans>
需要注意的是:这部分配置需要放置在配置文件的最下面,否则会报错。
3. 激活profile
方法1. web.xml配置
<!-- 配置spring的profile --> <context-param> <param-name>spring.profiles.active</param-name> <param-value>development</param-value> </context-param>
方法2. Tomcat 启动脚本 catalina.bat 设置
set JAVA_OPTS="-Dspring.profiles.active=test"