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

网友投稿 299 2022-08-18


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

目录如何获取yml的自定义参数需求实现方式自定义yml文件,获取配置参数操作yml文件依赖mqtt链接参数,及读取yml文件工具MqttParams.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 文件位置


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Springboot如何获取yml、properties参数
下一篇:SpringBoot整合数据库访问层的实战
相关文章

 发表评论

暂时没有评论,来抢沙发吧~