站长工具查询seo,忻州网站建设公司,网站重要性,广州app搭建再来个文章目录 文章目录前言1、自定义配置文件2、配置对象类3、YamlPropertiesSourceFactory下面还有投票#xff0c;帮忙投个票#x1f44d;
前言
最近在看某个开源项目代码并准备参与其中#xff0c;代码过了一遍后发现多个自定义的配置文件用来装载业务配置代替数据库… 再来个文章目录
文章目录前言1、自定义配置文件2、配置对象类3、YamlPropertiesSourceFactory下面还有投票帮忙投个票
前言
最近在看某个开源项目代码并准备参与其中代码过了一遍后发现多个自定义的配置文件用来装载业务配置代替数据库查询直接响应给前端这里简单记录一下实现过程。
我们通常在SpringBoot项目中用配置文件属性时使用ConfigurationProperties或Value默认配置文件的属性值也就是application.yml或者application.properties文件中的属性值。
但是不能全都往默认配置文件里堆的本文利用PropertySource和ConfigurationProperties注解引用其它配置文件的属性值。
1、自定义配置文件
在resources下创建my.yaml文件“-”用来表示数组类型一定要注意空格。
my:contents:- id: 12121name: nadasd- id: 3333name: 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 Listcontent contents new ArrayList();public Listcontent getContents() {return contents;}public void setContents(Listcontent 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属性如下
name默认为空不指定Spring自动生成value配置文件ignoreResourceNotFound没有找到配置文件是否忽略默认false4.0版本加入encoding配置文件编码格式默认UTF-8 4.3版本才加入factory配置文件解析工厂默认PropertySourceFactory.class 4.3版本才加入如果是之前的版本就需要手动注入配置文件解析Bean
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 {Overridepublic PropertySource? createPropertySource(String name, EncodedResource resource) throws IOException {String resourceName Optional.ofNullable(name).orElse(resource.getResource().getFilename());ListPropertySource? yamlSources new YamlPropertySourceLoader().load(resourceName, resource.getResource());return yamlSources.get(0);}}