springboot如何獲取yml文件的自定義參數(shù)
如何獲取yml的自定義參數(shù)
需求
通過yml文件配置參數(shù),在需要的地方獲取并使用參數(shù)
實現(xiàn)方式
方式一:
先上要獲取的配置參數(shù),在用到參數(shù)的位置獲取yml文件里面配好的值,如果就一兩個地方用到,那直接寫死也不是不行,但是最好通過配置文件的方式,萬一參數(shù)變了,只要改配置文件就行,業(yè)務代碼不用動
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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring實戰(zhàn)之獲得Bean本身的id操作示例
這篇文章主要介紹了Spring實戰(zhàn)之獲得Bean本身的id操作,結合實例形式分析了spring獲取Bean本身id的相關配置與實現(xiàn)技巧,需要的朋友可以參考下2019-11-11Eclipse 導出可執(zhí)行Java工程/可執(zhí)行Jar文件(包含第三方Jar包)
這篇文章主要介紹了Eclipse 導出可執(zhí)行Java工程/可執(zhí)行Jar文件(包含第三方Jar包)的相關資料,需要的朋友可以參考下2016-11-11SpringBoot @JsonDeserialize自定義Json序列化方式
這篇文章主要介紹了SpringBoot @JsonDeserialize自定義Json序列化方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10