这里的问题是区分
PropertySourcesPlaceholderConfigurer和
StandardServletEnvironment,或
Environment为简单起见。
的
Environment是,备份整个对象
ApplicationContext,并且可以解决一束性质(所述
Environment接口延伸
PropertyResolver)。A
ConfigurableEnvironment有一个
MutablePropertySources您可以通过检索的对象
getPropertySources()。它
MutablePropertySources包含要检查
linkedList的
PropertySource对象,以解析请求的属性。
PropertySourcesPlaceholderConfigurer是具有自己状态的单独对象。它拥有自己的
MutablePropertySources用于解析属性占位符的对象。
PropertySourcesPlaceholderConfigurer实现,
EnvironmentAware以便在
ApplicationContext获取它时为其提供
Environment对象。在
PropertySourcesPlaceholderConfigurer添加此
Environment的
MutablePropertySources它自己的。然后,它还将添加
Resource您指定的各种对象
setLocation()作为附加属性。
这些
Resource对象不会加入
Environment的
MutablePropertySources,因此是不可用
env.getProperty(String)。
因此,您无法直接将加载
PropertySourcesPlaceholderConfigurer到的属性
Environment。你可以做的,而不是直接添加到
Environment的
MutablePropertySouces。一种方法是
@PostConstructpublic void setup() throws IOException { Resource resource = new FileSystemResource("spring.properties"); // your file Properties result = new Properties(); PropertiesLoaderUtils.fillProperties(result, resource); env.getPropertySources().addLast(new PropertiesPropertySource("custom", result));}或干脆(感谢@ M.Deinum)
@PostConstructpublic void setup() throws IOException { env.getPropertySources().addLast(new ResourcePropertySource("custom", "file:spring.properties")); // the name 'custom' can come from anywhere}注意,添加a
@PropertySource具有相同的效果,即。直接添加到中
Environment,但您是在静态而不是动态地进行操作。



