yml 自定义配置读取

由于项目需要,我们有时候会把一些动态的参数配置放置在yml文件里,例如外围系统的url,然后对其进行访问。这个时候,就需要在SpringBoot2.0下读取YML文件的属性值

maven依赖

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

 

application.yml中写入属性

system:
    xxxxsysUrl: http://127.0.0.1:8091/checkxxxxsys
    miniprogramUrl: http://127.0.0.1/miniprogram



MyProps的配置类,支持被@Autowired

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component  
@ConfigurationProperties(prefix="system") //接收application.yml中的system下面的属性  
public class MyProps {
    public String xxxsysUrl;
    public String miniprogramUrl;
    public String getXxxsysUrl() {
        return xxxsysUrl;
    }
    public void setXxxsysUrl(String xxxsysUrl) {
        this.xxxsysUrl = xxxsysUrl;
    }
    public String getMiniprogramUrl() {
        return miniprogramUrl;
    }
    public void setMiniprogramUrl(String miniprogramUrl) {
        this.miniprogramUrl = miniprogramUrl;
    }
}


MyProps调用实战
    //注入配置类
   

@Autowired
    MyProps myProps;

    @Override
    public String getCheckResult(String checkDate,String checkNum, String projectid) {
        System.out.println(""+myProps.getXxxsysUrl());
        try {
        //根据配置文件动态请求接口
            String responseStr=HttpUtil.get(myProps.getXxxsysUrl()+"/xxxcollectxxx/"+checkDate+"/"+checkNum+"/"+projectid);
            System.out.println(responseStr);
            return responseStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



后话

myYml:
  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
    private 

List> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
    private List listProp2 = new ArrayList<>(); //接收prop2里面的属性值
    private Map mapProps = new HashMap<>(); //接收prop1里面的属性值


--------------------- 
作者:Moshow郑锴 
来源:CSDN 
原文:https://blog.csdn.net/moshowgame/article/details/80353495 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(Java,SpringBoot)