这篇“springboot解析怎么指定yaml配置文件”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“springboot解析怎么指定yaml配置文件”文章吧。
1、自定义配置文件
在resources下创建my.yaml文件,“-”用来表示数组类型,一定要注意空格。
my: contents: - id: 12121 name: nadasd - id: 3333 name: vfffff
2、配置对象类
创建配置类对象,在类上添加@Component、@PropertySource、@ConfigurationProperties注解。
@Component是将该类交由spring管理,@PropertySource用来指定配置文件及解析Yaml格式,@ConfigurationProperties是将解析后的配置文件属性自动注入该类的属性。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@PropertySource(value = "classpath:my.yaml", factory = YamlPropertiesSourceFactory.class)
@ConfigurationProperties(prefix = "my")
public class MyProperties {
private List contents = new ArrayList();
public List getContents() {
return contents;
}
public void setContents(List contents) {
this.contents = contents;
}
}
class content {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@PropertySource注解是Spring用于加载配置文件,@PropertySource属性如下:
Spring Boot 默认不支持@PropertySource读取yaml 文件,需要自定义PropertySourceFactory进行解析。
3、YamlPropertiesSourceFactory
创建YamlPropertiesSourceFactory类用来解析Yaml格式的文件。
import org.springframework.boot.env.YamlPropertySourceLoader;
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.List;
import java.util.Optional;
public class YamlPropertiesSourceFactory implements PropertySourceFactory {
@Override
public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
List<PropertySource> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
return yamlSources.get(0);
}
}
以上就是关于“springboot解析怎么指定Yaml配置文件”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注云服务器网(yuntue.com)行业资讯频道。
本文来源:https://www.yuntue.com/post/47437.html | 云服务器网,转载请注明出处!

微信扫一扫打赏
支付宝扫一扫打赏