资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

使用springboot如何实现获取配置文件中的属性值

本篇文章给大家分享的是有关使用springboot如何实现获取配置文件中的属性值,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

10年积累的成都做网站、成都网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站策划后付款的网站建设流程,更有云溪免费网站建设让你可以放心的选择与我们合作。

在spring boot中,简单几步,读取配置文件(application.yml)中各种不同类型的属性值:

1、引入依赖:

 
 
  org.springframework.boot 
  spring-boot-configuration-processor 
  true 
 

2、配置文件(application.yml)中配置各个属性的值:

myProps: #自定义的属性和值 
 simpleProp: simplePropValue 
 arrayProps: 1,2,3,4,5 
 listProp1: 
  - name: abc 
   value: abcValue 
  - name: efg 
   value: efgValue 
 listProp2: 
  - config2Value1 
  - config2Vavlue2 
 mapProps: 
  key1: value1 
  key2: value2 

3、创建一个bean来接收配置信息:

@Component 
@ConfigurationProperties(prefix="myProps") //接收application.yml中的myProps下面的属性 
public class MyProps { 
  private String simpleProp; 
  private String[] arrayProps; 
  private List> listProp1 = new ArrayList<>(); //接收prop1里面的属性值 
  private List listProp2 = new ArrayList<>(); //接收prop2里面的属性值 
  private Map mapProps = new HashMap<>(); //接收prop1里面的属性值 
   
  public String getSimpleProp() { 
    return simpleProp; 
  } 
   
  //String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要 
  public void setSimpleProp(String simpleProp) { 
    this.simpleProp = simpleProp; 
  } 
   
  public List> getListProp1() { 
    return listProp1; 
  } 
  public List getListProp2() { 
    return listProp2; 
  } 
 
  public String[] getArrayProps() { 
    return arrayProps; 
  } 
 
  public void setArrayProps(String[] arrayProps) { 
    this.arrayProps = arrayProps; 
  } 
 
  public Map getMapProps() { 
    return mapProps; 
  } 
 
  public void setMapProps(Map mapProps) { 
    this.mapProps = mapProps; 
  } 
} 

启动后,这个bean里面的属性就会自动接收配置的值了。

4、单元测试用例:

@Autowired 
  private MyProps myProps;  
   
  @Test 
  public void propsTest() throws JsonProcessingException { 
    System.out.println("simpleProp: " + myProps.getSimpleProp()); 
    System.out.println("arrayProps: " + objectMapper.writeValueAsString(myProps.getArrayProps())); 
    System.out.println("listProp1: " + objectMapper.writeValueAsString(myProps.getListProp1())); 
    System.out.println("listProp2: " + objectMapper.writeValueAsString(myProps.getListProp2())); 
    System.out.println("mapProps: " + objectMapper.writeValueAsString(myProps.getMapProps())); 
  } 

测试结果:

simpleProp: simplePropValue 
arrayProps: ["1","2","3","4","5"] 
listProp1: [{"name":"abc","value":"abcValue"},{"name":"efg","value":"efgValue"}] 
listProp2: ["config2Value1","config2Vavlue2"] 
mapProps: {"key1":"value1","key2":"value2"} 

以上就是使用springboot如何实现获取配置文件中的属性值,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


标题名称:使用springboot如何实现获取配置文件中的属性值
网站链接:http://cdkjz.cn/article/jehehg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220