SpringBoot 使用 @PropertySource 加载自定义 yml 文件 | LIXI.FUN
0%

SpringBoot 使用 @PropertySource 加载自定义 yml 文件

@PropertySource 本身 支持 .properties 格式的文件,后缀可以不为 .properties,但是内容格式得按照 .properties 的格式来。

例如:

my.properties

1
2
myp.name=lixi
myp.age=8
1
2
3
4
5
6
7
8
9
10
/**
* 当直接指定 .properties 文件的时候,可以正常拿到值
*/
@PropertySource(value = "classpath:my.properties")

/**
* 当直接指定 .yml 文件的时候
* 并不能拿到文件中的属性的值,所有的引用类型为 `null`,基本类型为其默认值
*/
@PropertySource(value = "classpath:my.yml")

如果想要 @PropertySource 读取 .yml 格式的文件需要自定义 YamlPropertySourceFactory

1
2
3
myy:
name: lixifun
age: 88

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 的代码内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
}
}
觉得有收获就鼓励下作者吧