服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - 浅谈spring注解之@profile

浅谈spring注解之@profile

2021-01-18 09:45PointNet JAVA教程

这篇文章主要介绍了浅谈spring注解之@profile,@profile通过配置来改变参数,这里整理的详细的用法,有兴趣的可以了解一下

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

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

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

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

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

一、注解配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/** 配置生产环境调用类 **/
@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配置

?
1
2
3
4
5
6
7
8
9
<!-- 开发环境 -->
<beans profile="dev">
  <bean id="beanname" class="com.pz.demo.ProductRPC"/>
</beans>
 
<!-- 生产环境 -->
<beans profile="dev">
  <bean id="beanname" class="com.pz.demo.MockProductRPC"/>
</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
2
3
4
<context-param>
  <param-name>spring.profiles.default</param-name>
  <param-value>dev</param-value>
</context-param>

2.作为DispatcherServlet的初始化参数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<servlet>
  <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进行激活

?
1
2
3
4
5
6
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/spring-config.xml")
@ActiveProfiles("dev")
public class MainTest {
  ...
}

4.作为JNDI条目

5.作为环境变量

6.作为JVM的系统属性

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/goody9807/p/7660480.html?utm_source=tuicool&utm_medium=referral

延伸 · 阅读

精彩推荐