由于项目需要,我们有时候会把一些动态的参数配置放置在yml文件里,例如外围系统的url,然后对其进行访问。这个时候,就需要在SpringBoot2.0下读取YML文件的属性值
maven依赖
<!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
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<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值
private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值