【问题标题】:How to get map of all properties in Spring application?如何获取 Spring 应用程序中所有属性的映射?
【发布时间】:2025-12-02 14:45:02
【问题描述】:

假设我们有一个Spring 5+ 应用程序。

如何获取application-[env] 文件中指定的所有属性的集合?弄清楚每个属性的起源概况也很有趣。

我想应该有一个标准的方法来做到这一点,但没有设法在网络上找到任何提及。

【问题讨论】:

标签: spring spring-profiles


【解决方案1】:

从 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)

【讨论】:

    最近更新 更多