一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

浅谈spring注解之@profile

时间:2017-10-23 编辑:猪哥 来源:一聚教程网

spring中@profile与maven中的profile很相似,通过配置来改变参数。

例如在开发环境与生产环境使用不同的参数,可以配置两套配置文件,通过@profile来激活需要的环境,但维护两套配置文件不如maven中维护一套配置文件,在pom中通过profile来修改配置文件的参数来的实惠。

也有例外,比如我在开发中调用商城接口经常不能返回我需要的数据,每次都需要mock数据,所以我写了一个mock参数的借口调用类,在开发环境中就使用这个类,测试环境与生产环境则使用正常的借口调用类,这样就不用每次开发的时候去手动改一些代码。

注:@profile在3.2以后的版本支持方法级别和类级别,3.1版本只支持类级别。

言归正传,说下@profile使用方法。

一、注解配置

/** 配置生产环境调用类 **/ 
@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接口。

二、XML配置

 
 
   
 
 
 
 
   
 

三、激活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)

  
  spring.profiles.default 
  dev 
 

2.作为DispatcherServlet的初始化参数

 
  springMVC 
  org.springframework.web.servlet.DispatcherServlet 
   
    contextConfigLocation 
    classpath:/spring-servlet.xml 
   
   
    spring.profiles.default 
    dev 
   
  1 
 

3.spring-junit使用@ActiveProfiles进行激活

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "/spring-config.xml") 
@ActiveProfiles("dev") 
public class MainTest { 
  ... 
} 

4.作为JNDI条目

5.作为环境变量

6.作为JVM的系统属性

热门栏目