Spring Boot @ConfigurationProperties YAML 引用 [英] Spring Boot @ConfigurationProperties YAML referencing
问题描述
我真的很喜欢 Spring 的 @ConfigurationProperties 功能,它通过 YAML 将我的配置属性加载到 Java 类中.
I really like the @ConfigurationProperties-functionality of Spring to load my configuration properties via YAML into a Java class.
通常我会以某种方式使用它,即我有以下 yaml 文件:
Normally I would use it in a way, that I have the following yaml-file:
lst:
typ:
A: "FLT"
B: "123"
C: "345"
D: "TTS"
type-attribute 将被映射到 Java-Map.现在我想有一个解决方案来引用 yaml 文件本身中的 yaml-fragments,以便我可以重用对片段的引用:
The type-attribute would be mapped to a Java-Map. Now i would like to have a solution to reference yaml-fragments in the yaml-file itself, so that I could reuse the reference to the fragment:
lst: ${typs}
typs:
A: "FLT"
B: "123"
C: "345"
D: "TTS"
使用 Spring 和 @ConfigurationProperties 可以吗?
Is that possible with Spring and @ConfigurationProperties?
推荐答案
我相信只能使用带有字符串属性的占位符.这给您留下了 2 个选择:
I believe it is only possible to use placeholder with string properties. This leaves you with 2 options:
- 重复这些值;
- OR 将地图定义为属性字符串(来源:https://stackoverflow.com/a/28370899/641627).
- repeat the values;
- OR define the map as a String of properties (source: https://stackoverflow.com/a/28370899/641627).
如果您单击上面的链接,则会提供完整的说明.我会带你完成它.
The whole explanation is provided if you click on the link above. I'll walk you through it.
prop1: A:FLT, B:123, C...
prop2: ${prop1}
(2) 定义一个字符串来映射转换器/拆分器(来自 @FedericoPeraltaSchaffner 的回答)
@Component("PropertySplitter")
public class PropertySplitter {
public Map<String, String> map(String property) {
return this.map(property, ",");
}
private Map<String, String> map(String property, String splitter) {
return Splitter.on(splitter).omitEmptyStrings().trimResults().withKeyValueSeparator(":").split(property);
}
}
(3) 使用@Value 和splitter 注入地图:
@Value("#{PropertySplitter.map('${prop1}')}")
Map<String, String> prop1;
@Value("#{PropertySplitter.map('${prop2}')}")
Map<String, String> prop2;
这篇关于Spring Boot @ConfigurationProperties YAML 引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!