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文件依赖
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.29</version> </dependency>
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 文件位置

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
