繁体   English   中英

使用Spring Boot 2以编程方式将yaml字符串转换为ConfigurationProperties

[英]Programatically convert yaml string to ConfigurationProperties with Spring Boot 2

我有一个第三方库,其中提供了用于ConfigurationProperties的类,例如:

@ConfigurationProperties(prefix = "foo")
public class AnimalProperties {

    private List<Treats> treats = new ArrayList<>();
...
}

在Spring Boot 2中,将Yaml字符串(以编程方式构造)绑定到AnimalProperties实例的最简单方法是什么? 例如,给定字符串:

treats:
  -
    name: treat1
    flavour: sweet
  -
    name: treat2
    flavour: sour

在Spring Boot 1.x中,可以使用YamlConfigurationFactory完成此操作,但是在Spring Boot 2中不再存在。

例如:

    YamlConfigurationFactory<AnimalProperties> animalConfigFactory = new YamlConfigurationFactory<>(
            AnimalProperties.class);
    animalConfigFactory.setYaml("{ treats: " + treatYalm + " }");
    try {
        animalConfigFactory.afterPropertiesSet();
        treats.addAll(animalConfigFactory.getObject().getTreats());
    }
    ...

不幸的是,Spring Boot 2.x中没有YamlConfigurationFactory直接替代品。 实际上,至少从我的研究YamlConfigurationFactory ,从源头上看,似乎在Spring Boot内部没有实际使用YamlConfigurationFactory

但是YamlConfigurationFactory内部仅使用snakeyaml ,因此可能类似于:

import org.yaml.snakeyaml.Yaml;

Yaml yaml = new Yaml();
String myYamlString = "...."
AnimalProperties animalProps = yaml.loadAs(myYamlString, AnimalProperties.class)

真正唯一的缺点是您会失去实现InitializingBean接口后afterPropertiesSet执行的验证。


如果该yml字符串仅在application.yml定义为:

foo:
  treats:
    -
      name: treat1
      flavour: sweet
    -
      name: treat2
      flavour: sour

那么您可以像注入任何bean一样注入它:

@Service
public class ExampleService {
    private final AnimalProperties animalProperties;

    public ExampleService(AnimalProperties animalProperties) {
        this.animalProperties = animalProperties;
    }
}

创建AnimalProperties时,Spring将在启动时进行bean验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM