我想知道,是否有一种通用方法可以用您只知道前缀的属性填充地图。
假设有一堆属性,比如
namespace.prop1=value1
namespace.prop2=value2
namespace.iDontKnowThisNameAtCompileTime=anothervalue
我想要一种通用的方法来在地图中填充这个属性,比如
@Component
@ConfigurationProperties("namespace")
public class MyGenericProps {
private Map<String, String> propmap = new HashMap<String, String>();
// setter and getter for propmap omitted
public Set<String> returnAllKeys() {
return propmap.keySet();
}
}
或者是否有另一种方便的方法来收集具有特定前缀的所有属性,而不是遍历环境中的所有 PropertySources?
感谢 Hansjoerg
原文由 Hansjoerg Wingeier 发布,翻译遵循 CC BY-SA 4.0 许可协议
只要您愿意将每个属性添加到地图中,而不仅仅是那些您事先不知道的属性,您就可以使用
@ConfigurationProperties
来完成。如果您想获取namespace
下面的所有内容,那么您需要使用空前缀并为名为namespace
的地图提供一个 getter:Spring Boot 使用
getNamespace
方法来检索映射,以便它可以向其中添加属性。具有这些属性:namespace
地图将包含三个条目:如果属性嵌套得更深,例如:
Then you’d use
namespace.foo
as the prefix and renamenamespace
andgetNamespace
onCustomProperties
tobar
andgetBar
分别。请注意,您应该将
@EnableConfigurationProperties
应用于您的配置以启用对@ConfigurationProperties
的支持。然后,您可以使用该注释引用您想要处理的任何 beans,而不是为它们提供@Bean
方法,或使用@Component
让它们通过组件扫描发现: