PropertySourcesPlaceholderConfigurer直接读取属性文件(就像在Spring
3.0中PropertyPlaceholderConfigurer所做的那样),它只是一个后处理器,不会改变在Spring上下文中使用属性的方式-
在这种情况下,属性仅可用作bean定义占位符。
使用Environment的是PropertySourcesPlaceholderConfigurer,反之亦然。
属性源框架在应用程序上下文级别上工作,而属性占位符配置器仅提供在Bean定义中处理占位符的功能。要使用属性源抽象,您应该使用
@PropertySource注释,即用类似的东西装饰您的配置类
@PropertySource("classpath:SpringConfig.properties")我相信您可以通过编程方式执行相同的操作,即可以在刷新上下文之前获取容器的ConfigurableEnvironment,通过修改其MutablePropertySources(首先需要
AbstractApplicationContext
environment通过来获取属性
context.getEnvironment()
),
getPropertySources().addFirst(new ResourcePropertySource(newClassPathResource( "SpringConfig.properties")));但这不太可能您想做的事情-
如果您已经拥有一个带
@Configuration注释的类,用它装饰起来
@PropertySource("classpath:SpringConfig.properties")要简单得多。至于
PropertySourcesPlaceholderConfigurer实例-
它会自动从其应用程序上下文中获取属性源(因为它实现EnvironmentAware),因此您只需要注册它的默认实例即可。
有关自定义属性源实现的示例,请参见http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-
property-
management/



