springboot自定义yaml配置文件
2021-03-10 17:28
标签:als pat obj eof ati des encode port java Spring Boot的默认不支持yaml文件,需要自定义一个factory @Configuration
@PropertySource(value springboot自定义yaml配置文件 标签:als pat obj eof ati des encode port java 原文地址:https://www.cnblogs.com/patrick-king/p/14145527.htmlimport 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.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* @version 0.1.0
* @description: 解析自定义yml文件
* @author: Patrick
* @create 2020-12-14 11:07
**/
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource> createPropertySource(String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
上一篇:3. Java基础语法
下一篇:二叉排序树
文章标题:springboot自定义yaml配置文件
文章链接:http://soscw.com/index.php/essay/62851.html