spring中@profile与maven中的profile很类似,经过配置来改变参数。
例如在开发环境与生产环境使用不一样的参数,能够配置两套配置文件,经过@profile来激活须要的环境,但维护两套配置文件不如maven中维护一套配置文件,在pom中经过profile来修改配置文件的参数来的实惠。
html
也有例外,好比我在开发中调用商城接口常常不能返回我须要的数据,每次都须要mock数据,因此我写了一个mock参数的借口调用类,在开发环境中就使用这个类,测试环境与生产环境则使用正常的借口调用类,这样就不用每次开发的时候去手动改一些代码。java
注:@profile在3.2之后的版本支持方法级别和类级别,3.1版本只支持类级别。
言归正传,说下@profile使用方法。
web
1、注解配置spring
- @service("productRpc")
- @profile("prop")
- public class ProductRpcImpl implements ProductRpc
- public String productBaseInfo(Long sku){
- return productResource.queryBaseInfo(Long sku);
- }
- }
-
-
- @service("productRpc")
- @profile("dev")
- public class MockProductRpcImpl implements ProductRpc
- public String productBaseInfo(Long sku){
- return “iphone7”;
- }
- }
-
- public class Demo(){
- @Resource(name="productRpc")
- private ProductRpc productRpc;
-
- public void demo(){
- String skuInfo = productRpc.productBaseInfo(123123L);
- logger.info(skuInfo);
- }
- }
这样就完成了基于注解的profile配置。当配置为生产环境的时候会正常调用接口,当为开发环境的时候回调用mock接口。
2、XML配置iphone
- <beans profile="dev">
- <bean id="beanname" class="com.pz.demo.ProductRPC"/>
- </beans>
-
- <beans profile="dev">
- <bean id="beanname" class="com.pz.demo.MockProductRPC"/>
- </beans>
3、激活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)maven
- <context-param>
- <param-name>spring.profiles.default</param-name>
- <param-value>dev</param-value>
- </context-param>
2.做为DispatcherServlet的初始化参数测试
- ervlet>
- <servlet-name>springMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:/spring-servlet.xml</param-value>
- </init-param>
- <init-param>
- <param-name>spring.profiles.default</param-name>
- <param-value>dev</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
3.spring-junit使用@ActiveProfiles进行激活spa
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = "/spring-config.xml")
- @ActiveProfiles("dev")
- public class MainTest {
- ...
- }
4.做为JNDI条目
5.做为环境变量
6.做为JVM的系统属性xml