![](/img/trans.png)
[英]Spring Boot + Yaml + @PropertySource + @ConfigurationProperties + List in Property Source file not injecting
[英]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.