只需要创建一个类
1import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
2import org.springframework.core.env.PropertiesPropertySource;
3import org.springframework.core.env.PropertySource;
4import org.springframework.core.io.support.DefaultPropertySourceFactory;
5import org.springframework.core.io.support.EncodedResource;
6
7import java.io.IOException;
8import java.util.Properties;
9
10public class YmlConfigFactory extends DefaultPropertySourceFactory {
11 @Override
12 public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
13 String sourceName = name != null ? name : resource.getResource().getFilename();
14 if (!resource.getResource().exists()) {
15 //不存在就返回一个空的把
16 return new PropertiesPropertySource(sourceName, new Properties());
17 }
18 if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
19 //yml这里手动加进去
20 YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
21 factory.setResources(resource.getResource());
22 factory.afterPropertiesSet();
23 Properties propertiesFromYaml = factory.getObject();
24 return new PropertiesPropertySource(sourceName, propertiesFromYaml);
25 }
26 return super.createPropertySource(name, resource);
27 }
28}