如何使用 Spring 的 `PropertySourcesPlaceholderConfigurer` 读取环境变量而非系统 属性

How to use Spring's `PropertySourcesPlaceholderConfigurer` to read environment variable NOT system property

Spring 3.1 PropertySourcesPlaceholderConfigurer javadoc 说:

This class is designed as a general replacement for PropertyPlaceholderConfigurer in Spring 3.1 applications.

但我没有看到一个明显的方法来复制 PropertyPlaceholderConfigurersearchSystemEnvironment 属性 的功能,这使得配置器寻找一个环境变量当找不到与占位符名称匹配的系统属性时。

请注意,我在 SO 上看到了很多关于 "environment variables" 和 PropertySourcesPlaceholderConfigurer 的问题,但我看到的每个问题都是 实际上 问的关于系统属性,而不是环境变量。

如何告诉 PropertySourcesPlaceholderConfigurer 回退到使用环境变量提供占位符值?

首先要注意的是 Javadoc

中的这个片段

Any local properties (e.g. those added via PropertiesLoaderSupport.setProperties(java.util.Properties), PropertiesLoaderSupport.setLocations(org.springframework.core.io.Resource...) et al.) are added as a PropertySource. Search precedence of local properties is based on the value of the localOverride property, which is by default false meaning that local properties are to be searched last, after all environment property sources.

换句话说,PropertySourcesPlaceholderConfigurer 有自己的 local 属性 来源,默认情况下,它在 属性 之后搜索直接在环境中注册的来源,即。 ConfigurableEnvironment.

类型的实例

ConfigurableEnvironment 的 Javadoc,在 getSystemPropeties() and getSystemEnvironment() 中继续说

Return the value of System.getProperties() if allowed by the current SecurityManager, otherwise return a map implementation that will attempt to access individual keys using calls to System.getProperty(String).

Note that most Environment implementations will include this system properties map as a default PropertySource to be searched.

[...]

Return the value of System.getenv() if allowed by the current SecurityManager, otherwise return a map implementation that will attempt to access individual keys using calls to System.getenv(String)

Note that most Environment implementations will include this system environment map as a default PropertySource to be searched.

这些 Environment 实现 StandardEnvironment,这是默认的 Spring 的 ApplicationContext class es 使用。

这个 class Javadoc 指出

In addition to the usual functions of a ConfigurableEnvironment such as property resolution and profile-related operations, this implementation configures two default property sources, to be searched in the following order:

  • system properties
  • system environment variables

That is, if the key "xyz" is present both in the JVM system properties as well as in the set of environment variables for the current process, the value of key "xyz" from system properties will return from a call to environment.getProperty("xyz"). This ordering is chosen by default because system properties are per-JVM, while environment variables may be the same across many JVMs on a given system. Giving system properties precedence allows for overriding of environment variables on a per-JVM basis.

这些 属性 源是可变的和可重新排序的。但是,为了回答您的问题,您请求的行为已经默认提供。