spring中@profile与maven中的profile很相似,通过配置来改变参数。
例如在开发环境与生产环境使用不同的参数,可以配置两套配置文件,通过@profile来**需要的环境,但维护两套配置文件不如maven中维护一套配置文件,在pom中通过profile来修改配置文件的参数来的实惠。
也有例外,比如我在开发中调用商城接口经常不能返回我需要的数据,每次都需要mock数据,所以我写了一个mock参数的借口调用类,在开发环境中就使用这个类,测试环境与生产环境则使用正常的借口调用类,这样就不用每次开发的时候去手动改一些代码。
注:@profile在3.2以后的版本支持方法级别和类级别,3.1版本只支持类级别。
言归正传,说下@profile使用方法。
一、注解配置
[java] view plain copy
1. /** 配置生产环境调用类 **/
2. @service("productRpc")
3. @profile("prop")
4. public class ProductRpcImpl implements ProductRpc
5. public String productBaseInfo(Long sku){
6. return productResource.queryBaseInfo(Long sku);
7. }
8. }
9.
10.
11. /** 配置生产环境调用类 **/
12. @service("productRpc")
13. @profile("dev")
14. public class MockProductRpcImpl implements ProductRpc
15. public String productBaseInfo(Long sku){
16. return “iphone7”;
17. }
18. }
19.
20. /** 调用类 **/
21. public class Demo(){
22. @Resource(name="productRpc")
23. private ProductRpc productRpc;
24.
25. public void demo(){
26. String skuInfo = productRpc.productBaseInfo(123123L);
27. logger.info(skuInfo);
28. }
29. }
这样就完成了基于注解的profile配置。当配置为生产环境的时候会正常调用接口,当为开发环境的时候回调用mock接口。
二、XML配置
1. <!-- 开发环境 -->
2. <beans profile="dev">
3. <bean id="beanname" class="com.pz.demo.ProductRPC"/>
4. </beans>
5.
6. <!-- 生产环境 -->
7. <beans profile="dev">
8. <bean id="beanname" class="com.pz.demo.MockProductRPC"/>
9. </beans>
二、 **profile
注:spring在确定那个profile处于**状态的时,需要依赖两个独立的属性:spring.profiles.active和spring.profile.default。如果设置了spring.profiles.actives属性,那么它的值就会用来确定那个profile是**的。如果没有设置spring.profiles.active属性的话,那spring将会查找spring.profiles.default的值。如果spring.profiles.active和spring.profiles.default均没有设置。(红色部分未在项目中验证成功,待测试)
1.在servlet上下文中进行配置(web.xml)
1. <context-param>
2. <param-name>spring.profiles.default</param-name>
3. <param-value>dev</param-value>
4. </context-param>
2.作为DispatcherServlet的初始化参数
1. ervlet>
2. <servlet-name>springMVC</servlet-name>
3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
4. <init-param>
5. <param-name>contextConfigLocation</param-name>
6. <param-value>classpath:/spring-servlet.xml</param-value>
7. </init-param>
8. <init-param>
9. <param-name>spring.profiles.default</param-name>
10. <param-value>dev</param-value>
11. </init-param>
12. <load-on-startup>1</load-on-startup>
13. </servlet>
3.spring-junit使用@ActiveProfiles进行**
1. @RunWith(SpringJUnit4ClassRunner.class)
2. @ContextConfiguration(locations = "/spring-config.xml")
3. @ActiveProfiles("dev")
4. public class MainTest {
5. ...
6. }
4作为JNDI条目
5作为环境变量
ConfigurableEnvironment.setActiveProfiles("test")
6作为JVM的系统属性
tomcat 中catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通过设置active选择不同配置文件
set JAVA_OPTS="-Dspring.profiles.active=test"
eclipse中启动tomcat。项目右键 run as – > runconfiguration–>Arguments–> VM arguments中添加。local配置文件不必上传git追踪管理
-Dspring.profiles.active="local"
7application.properties配置文件
配置文件中添加:spring.profiles.active=prod
spring.profiles.default=dev
关注微信公众号和今日头条,精彩文章持续更新中。。。。。