【发布时间】:2025-12-02 14:45:02
【问题描述】:
假设我们有一个Spring 5+ 应用程序。
如何获取application-[env] 文件中指定的所有属性的集合?弄清楚每个属性的起源概况也很有趣。
我想应该有一个标准的方法来做到这一点,但没有设法在网络上找到任何提及。
【问题讨论】:
-
您可以注入 Environment 对象并在其上使用 getPropertySources()。请参阅抽象环境。
假设我们有一个Spring 5+ 应用程序。
如何获取application-[env] 文件中指定的所有属性的集合?弄清楚每个属性的起源概况也很有趣。
我想应该有一个标准的方法来做到这一点,但没有设法在网络上找到任何提及。
【问题讨论】:
从 Spring 应用程序上下文中获取 AbstractEnvironment 就足够了,并遍历其 EnumerablePropertySource 源,发现所有属性名称,然后从环境中按名称获取属性值。
AbstractEnvironment environment = getFromContext() /*i.e. Autowired*/;
var propsStream =
environment
.getPropertySources().stream()
.flatMap(ps -> {
if (ps instanceof EnumerablePropertySource) {
return Arrays.stream(((EnumerablePropertySource<?>) ps).getPropertyNames());
} else {
return Stream.empty(); // or handle differently
}
})
.distinct()
.map(name -> Tuple.of(name, environment.getProperty(name)));
// here Tuple is a dummy class for holding (name, value)
【讨论】: