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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章