springboot如何获取yml文件的自定义参数

这篇文章主要介绍了springboot如何获取yml文件的自定义参数,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

如何获取yml的自定义参数

需求

通过yml文件配置参数,在需要的地方获取并使用参数

实现方式

方式一:

先上要获取的配置参数,在用到参数的位置获取yml文件里面配好的值,如果就一两个地方用到,那直接写死也不是不行,但是最好通过配置文件的方式,万一参数变了,只要改配置文件就行,业务代码不用动

yml配置参数:

 Config文件

@Configuration //定义配置类 @Data //提供get set方法 @ConfigurationProperties(prefix = "xxx.smc") //yml配置中的路径 public class SmcConfig  { private String ip; private String name; private String password; }

具体使用

 方式二:

通过value注解的方式

自定义yml文件,获取配置参数

操作yml文件依赖

             org.yaml             snakeyaml             1.29  

mqtt链接参数,及读取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 文件位置 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持0133技术站。

以上就是springboot如何获取yml文件的自定义参数的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java