springboot-PropertySource无法加载yaml解决办法

@PropertySource只对properties文件可以进行加载,但对于yml或者yaml不能支持。

// 继承DefaultPropertySourceFactory
public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        Resource resourceResource = resource.getResource();
        if (!resourceResource.exists()) {
            return new PropertiesPropertySource(null, new Properties());
        } else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
            List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
            return sources.get(0);
        }
        return super.createPropertySource(name, resource);
    }
}

@Component
@Data
@PropertySource(value = {"classpath:person.yaml"}, factory = YamlAndPropertySourceFactory.class)
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
    private String name;
    private String age;
    private Map<String, Object> properties;
    private List<Object> item;
}



你可能感兴趣的:(springboot)