LIXI.FUN - SpringBoot 使用 @PropertySource 加载自定义 yml 文件
@PropertySource
本身 仅 支持 .properties
格式的文件,后缀可以不为 .properties
,但是内容格式得按照 .properties
的格式来。
例如:
my.properties
myp.name=lixi
myp.age=8
/**
* 当直接指定 .properties 文件的时候,可以正常拿到值
*/
@PropertySource(value = "classpath:my.properties")
/**
* 当直接指定 .yml 文件的时候
* 并不能拿到文件中的属性的值,所有的引用类型为 `null`,基本类型为其默认值
*/
@PropertySource(value = "classpath:my.yml")
如果想要 @PropertySource
读取 .yml
格式的文件需要自定义 YamlPropertySourceFactory
myy:
name: lixifun
age: 88
使用方式
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Data
@Configuration
@ConfigurationProperties(prefix = "myy")
@PropertySource(value = "classpath:my.yml", factory = YamlPropertySourceFactory.class)
public class MyYamlConfig {
private String name;
private Integer age;
}
YamlPropertySourceFactory.java 的代码内容:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
Resource resource = encodedResource.getResource();
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource);
Properties props = factory.getObject();
return new PropertiesPropertySource(resource.getFilename(), props);
}
}