我们在开发项目的时候总会遇到不同的环境,特别是一些比较大的项目通常有好几套不同的环境,例如:本地、测试、产品等不同环境,那么这时候修改配置环境的参数值就很麻烦,不同的环境有不同的参数值。那本文介绍如何使用Spring profile去解决这个问题。
步骤:
1.spring配置文件applicationContext.xml中添加多环境参数文件的相关配置:
<beans profile="default"> <!-- 默认加载,可用于开发环境 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:default.properties"/>
</bean>
</beans>
<beans profile="local"> <!--本地环境-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:local.properties"/>
</bean>
</beans>
<beans profile="test"> <!--测试环境-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:test.properties"/>
</bean>
</beans>
2.在web.xml中设置默认环境
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--Spring配置加载器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>test</param-value>
</context-param>
</web-app>
到这一步,如果你启动项目,那么会默认加载你在web.xml中配置的spring.profiles.default的参数值作为参数读取对应的配置文件,例如你配置的是test那么会根据applicationContext.xml中的环境配置去读取test.properties中的参数。
但这个时候有另外一个问题,就是我们还根据不同的环境去修改spring.profiles.default的参数值,这也比较麻烦,万一忘记改了就会导致很严重的问题。
3.根据不同环境激活对应配置
spring.profiles本身是有两个级别的,一就是default级别,就是默认级别,二是active级别,是激活级别。例如你如果没有配置active那么将读取default级别的配置文件,如果你配置了active级别那会优先读取active级别的环境配置。下面是不同的情况下如何设置active,本质是通过设置JVM启动参数来实现的。
3.1 tomcat启动项目
如果你用的是tomcat启动的,那么把bin下面的catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通过设置active选择不同配置文件
JAVA_OPTS="-Dspring.profiles.active=test"
在这里把测试环境下的tomcat配置成test,把开发环境下的tomcat配置为local,这样一来什么都不用改,配置了什么环境就会读取对应的配置文件。
3.2 eclipse中tomcat插件
eclipse 中启动tomcat。项目右键 run as –> run configuration–>Arguments–> VM arguments中添加
3.3 eclipse中使用maven插件启动项目
3.4 IDEA中使用maven插件启动项目
或者
这样就实现了不同环境自动读取对应配置文件的功能,避免了改来改去的麻烦了。
-Dspring.profiles.active="local"
tomcat-8.5.15-lot-client-platfrom/bin/catalina.sh
JAVA_OPTS="-Dspring.profiles.active=local"
此技能大家是否有get到呢?
参考资料:
http://www.cnblogs.com/pangguoming/p/5888871.html
http://edison87915.iteye.com/blog/2110258
http://blog.youkuaiyun.com/xvshu/article/details/51133786