在 Spring Boot 项目中resource目录下创建一个simple.yml文件

my:
  enjoy:
    website:
      - github
      - google
    open_source: spring
  like:
    food: chicken
    pc: Thinkpad,MacBookPro

方式一:使用 YamlMapFactoryBean 加载 yaml 文件为 Map,自行读取,示例如下:

@Data
@Component
public class SimpleYaml2 {
    private Map<String, Object> object = loadYaml();

    private static Map<String, Object> loadYaml() {
        YamlMapFactoryBean yaml = new YamlMapFactoryBean();
        yaml.setResources(new ClassPathResource("simple.yml"));
        return yaml.getObject();
    }
}

方式二:扩展 PropertySourceFactory,使它支持加载 yaml 文件

1.扩展 PropertySourceFactory,实现一个加载 yaml 文件的配置文件工厂类

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
        return sources.get(0);
    }
}

2.在 @PropertySource(value="xxx",factory="xxx") 中指定工厂为自定义加载 yaml 文件的配置文件工厂类

@Data
@Component
@ConfigurationProperties(prefix = "my.like")
@PropertySource(value = "classpath:simple.yml", factory = YamlPropertySourceFactory.class)
public class SimpleYaml3 implements InitializingBean {
    private String food;
    private List<String> pc;
}

hhhhh