env.getProperty不工作Spring PropertyPlaceholderConfigurer
我正在使用spring加载属性文件
当我获得财产价值时
@Value("${testkey}")
工作正常。
但是当我试图使用环境时
@Resource private Environment environment; environment.getProperty("testkey") // returning null
PropertyPlaceholderConfigurer
不会将其locations
的属性添加到Environment
。 使用Java配置,您可以使用@PropertySource
来执行此操作。
如果有人想要在不使用@PropertySource的情况下实现这一点
使用ApplicationContextInitializer接口及其随附的contextInitializerClasses servlet上下文参数。
在web.xml中添加它
contextInitializerClasses com.test.MyInitializer
并定义您的初始化程序
public class MyInitializer implements ApplicationContextInitializer { public void initialize(ConfigurableWebApplicationContext ctx) { PropertySource ps = new ResourcePropertySource(new ClassPathResource("sample.properties")); // handle exception ctx.getEnvironment().getPropertySources().addFirst(ps); } }
参考: Spring 3.1 M1:统一物业管理