springboot如何獲取yml文件的自定義參數(shù)
如何獲取yml的自定義參數(shù)
需求
通過yml文件配置參數(shù),在需要的地方獲取并使用參數(shù)
實現(xiàn)方式
方式一:
先上要獲取的配置參數(shù),在用到參數(shù)的位置獲取yml文件里面配好的值,如果就一兩個地方用到,那直接寫死也不是不行,但是最好通過配置文件的方式,萬一參數(shù)變了,只要改配置文件就行,業(yè)務(wù)代碼不用動
yml配置參數(shù):

Config文件
@Configuration //定義配置類
@Data //提供get set方法
@ConfigurationProperties(prefix = "xxx.smc") //yml配置中的路徑
public class SmcConfig {
private String ip;
private String name;
private String password;
}具體使用


方式二:
通過value注解的方式


自定義yml文件,獲取配置參數(shù)
操作yml文件依賴
<dependency> ? ? ? ? ? ? <groupId>org.yaml</groupId> ? ? ? ? ? ? <artifactId>snakeyaml</artifactId> ? ? ? ? ? ? <version>1.29</version> ?</dependency>
mqtt鏈接參數(shù),及讀取yml文件工具
public class MqttParamObj {
? ? public String mqttBrokerIp;
? ? public Short mqttBrokerPort;
? ? public String userName;
? ? public String password;
? ? public String mqttClientId;
? ? public static MqttParamObj readConfigFile(){
? ? ? ? MqttParamObj mqttParamObj = null;
? ? ? ? File file = new File(System.getProperty("user.dir") + "/MqttParams.yml");
? ? ? ? try {
? ? ? ? ? ? InputStream fileInputStream = new FileInputStream(file);
? ? ? ? ? ? if(Objects.nonNull(fileInputStream)){
? ? ? ? ? ? ? ? Yaml yaml = new Yaml();
? ? ? ? ? ? ? ? mqttParamObj = yaml.loadAs(fileInputStream, MqttParamObj.class);
? ? ? ? ? ? }
? ? ? ? } catch (FileNotFoundException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return mqttParamObj;
? ? }
}MqttParams.yml 文件位置

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中資源加載的方法及Spring的ResourceLoader應(yīng)用小結(jié)
在Java開發(fā)中,資源加載是一個基礎(chǔ)而重要的操作,這篇文章主要介紹了深入理解Java中資源加載的方法及Spring的ResourceLoader應(yīng)用,本文通過實例代碼演示了通過ClassLoader和Class獲取資源的內(nèi)容,以及使用Spring的ResourceLoader加載多個資源的過程,需要的朋友可以參考下2024-01-01
關(guān)于Intellij idea 報錯:Error : java 不支持發(fā)行版本5的問題
這篇文章主要介紹了關(guān)于Intellij idea 報錯:Error : java 不支持發(fā)行版本5的問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02
Spring使用@Autowired注解實現(xiàn)自動裝配方式
這篇文章主要介紹了Spring使用@Autowired注解實現(xiàn)自動裝配方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
關(guān)于IDEA創(chuàng)建spark maven項目并連接遠程spark集群問題
這篇文章主要介紹了IDEA創(chuàng)建spark maven項目并連接遠程spark集群,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08

