从.yml配置文件中读取属性值
从.yml配置文件中读取属性值
参考文章
springboot使用@PropertySource的默认factory是读取.properties文件属性。
如果要读取yml或者yaml格式的文件属性值,需要自定义一个YamlPropertySourceFactory
实现YamlPropertySourceFactory类
package com.example.demo.config;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
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;
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource)
throws IOException {
// 指定配置路径中的文件名
String filename = resource.getResource().getFilename() == null ? "" : resource.getResource().getFilename();
// 资源为空,则会抛出异常
resource.getInputStream();
// 配置文件为 properties 文件,调用原逻辑
if (resource == null || filename.endsWith(".properties")) {
return super.createPropertySource(name, resource);
}
// yml文件 或 yaml文件,则使用yaml属性源加载器加载并返回标准属性源
else if (filename.endsWith(".yml") || filename.endsWith(".yaml")) {
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
}
// 非以上情况,则直接抛出异常,提示格式错误
else {
throw new IOException("file format error! only support: properties, yml, yaml!");
}
}
}
关联的对象类
通过@PropertySource
来指定配置文件路径
package com.example.demo.config;
import lombok.Data;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@ConfigurationProperties(prefix = "test")
@Component
@PropertySource(value="classpath:test.yml",factory = YamlPropertySourceFactory.class, encoding = "utf-8")
@Data
public class TestConfig implements Serializable{
private String userName;
private String password;
}