解决PropertySource不能读取yml的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 解决PropertySource不能读取yml的问题
*
* @author: 李涛
* @version: 2020年03月26日 17:12
*/
public class YamlConfigFactory extends DefaultPropertySourceFactory {

@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = name != null ? name : resource.getResource().getFilename();
if (!resource.getResource().exists()) {
return new PropertiesPropertySource(sourceName, new Properties());
} else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
Properties propertiesFromYaml = loadYml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}

private Properties loadYml(EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}

使用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 用户自定义配置
*
* @author: 李涛
* @version: 2019年07月05日 16:44
*/

@PropertySource(value="classpath:file-table-config.yml",factory = YamlConfigFactory.class)
@ConfigurationProperties(prefix = "config")
@Component
@Data
public class FileTableConfig {

/***
* 表达式
*/
private String corn;

/***
* 表和资源字段
*/
private List<String> tables;

}

解决PropertySource不能读取yml的问题
https://kanchai.club/2022/12/10/解决PropertySource不能读取yml的问题/
作者
625
发布于
2022年12月10日
许可协议