SpringBoot 读取自定义 yaml 配置
前言
@ConfigurationProperties 方式
- 实现 PropertySourceFactory
package cn.phixlin.config;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;
/**
* @author
* @description
* @date 2024/11/22 15:49
*/
public class YmlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
factoryBean.setResources(resource.getResource());
factoryBean.afterPropertiesSet();
Properties properties = factoryBean.getObject();
String propertyName = name != null? name: resource.getResource().getFilename();
return new PropertiesPropertySource(propertyName, properties);
}
}
- 配置文件
remote:
proxy:
host: "**.***.**.**"
port: 8080
vms:
url: "http://api.map.baidu.com/direction"
ak: "******************"
amap:
url: "https://restapi.amap.com/v4/direction/truck"
key: "************"
deviate:
alert-producer-topic: line_alert_res
job-set:
start-delay-time: 1
finish-cover-time: 4320
interval-time: 1
biz-set:
distance-tolerate: 100
- 配置类
package cn.phixlin.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties()
@PropertySource(value = "classpath:myConfig.yml", encoding = "utf-8", factory = YmlPropertySourceFactory.class)
public class MyConf {
private Remote remote;
private Deviate deviate;
@Data
public static class Remote {
private Proxy proxy;
private Vms vms;
private AMap amap;
@Data
public static class Proxy {
private String host;
private String port;
}
@Data
public static class Vms {
private String url;
private String ak;
}
@Data
public static class AMap {
private String url;
private String key;
}
}
@Data
public static class Deviate {
private String alertProducerTopic;
private JobSet jobSet;
private BizSet bizSet;
@Data
public static class JobSet {
private String startDelayTime;
private String finishCoverTime;
private String intervalTime;
}
@Data
public static class BizSet {
private String distanceTolerate;
}
}
}
License:
CC BY 4.0