@PropertySource 不支持 YAML 的解决方案
原创2021/8/26小于 1 分钟
@PropertySource 不支持 YAML 的解决方案
(1)该注解是用来加载指定的配置文件的,但是默认情况下,它不支持 yaml 文件,只支持 properties 文件。
(2)默认的工厂接口是 PropertySourceFactory,默认的实现类是 DefaultPropertySourceFactory,所以我们来自定义一个工厂实现类 YamlPropertySourceFactory:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(resource.getResource().getFilename(), properties);
}
}(3)在使用的地方显示指定工厂实现类,如下:
@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
public class YamlFooProperties {
private String name;
private List<String> aliases;
// standard getter and setters
}foo.yml 文件:
yaml:
name: foo
aliases:
- abc
- xyz参考资料:

