Spring 3.1 Environment不适用于用户属性文件
问题内容:
我正在做..
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
xmlReader
.loadBeanDefinitions(new ClassPathResource("SpringConfig.xml"));
PropertySourcesPlaceholderConfigurer propertyHolder = new PropertySourcesPlaceholderConfigurer();
propertyHolder.setLocation(new ClassPathResource(
"SpringConfig.properties"));
context.addBeanFactoryPostProcessor(propertyHolder);
......
context.refresh();
现在在我的@Configuration文件中,如果执行此操作,则不会获取SpringConfig.properties中存在的属性…
@Autowired
private Environment env
.....
env.getProperty("my.property")
但是如果我使用该财产
@Value("${my.property}")
private String myProperty;
我什至尝试添加更多这样的行,但是没有用。
ConfigurableEnvironment env = new StandardEnvironment();
propertyHolder.setEnvironment(env);
有人知道为什么我的属性未加载到环境中吗?谢谢。
问题答案:
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(new ClassPathResource( "SpringConfig.properties")));
但这不太可能您想做的事情-
如果您已经拥有一个带@Configuration
注释的类,用它装饰起来@PropertySource("classpath:SpringConfig.properties")
要简单得多。
至于PropertySourcesPlaceholderConfigurer
实例-
它会自动从其应用程序上下文中获取属性源(因为它实现EnvironmentAware),因此您只需要注册它的默认实例即可。
有关自定义属性源实现的示例,请参见http://blog.springsource.org/2011/02/15/spring-3-1-m1-unified-
property-
management/