如何获取 Spring 应用程序中所有属性的映射?

How to get map of all properties in Spring application?

假设我们有一个 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)