工作中,时常遇到需要读取配置参数的情况,此处仅做一个记录。
一、yml配置文件
=> application.yml
# 自定义配置数据
customer:
cId: abcd
cKey: abcdefghijklmn
二、自定义参数工具类
用于设置和静态调用参数
public class CustomerInitUtil {
private static String cId;
private static String cKey;
public static String getCId() { return cId; }
public static void setCId(String cId) { TianyiVersionInitUtil.cId = cId; }
public static String getCKey() { return cKey; }
public static void setCKey(String cKey) { TianyiVersionInitUtil.cKey = cKey; }
}
三、自定义参数配置类
从配置文件读取字段值,且初始化配置
@Configuration
public class CustomerInitConfig {
// 从配置文件读取
@Value(value = "${customer.cId}")
private String cId;
@Value(value = "${customer.cKey}")
private String cKey;
@Bean
public void initCustomerInitConfig() {
CustomerInitUtil.setCId(cId);
CustomerInitUtil.setCKey(cKey);
}
}
四、调用示例
测试类无法使用配置调用(应该是因为未读取配置文件)
String cId = CustomerInitUtil.getCId();
String cKey = CustomerInitUtil.getCKey();