5

我正在使用弹簧加载属性文件

  <bean id="appProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="locations" value="classpath:/sample.properties" />
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

当我使用

@Value("${testkey}")它工作正常。

但是当我尝试使用 env

@Resource
 private Environment environment;

environment.getProperty("testkey") // returning null
4

2 回答 2

3

APropertyPlaceholderConfigurer不会将其属性添加locationsEnvironment. 使用 Java 配置,您可以使用它@PropertySource来执行此操作。

于 2014-05-27T17:58:14.990 回答
1

如果有人想在不使用@PropertySource 的情况下实现这一目标

使用 ApplicationContextInitializer 接口及其伴侣 contextInitializerClasses servlet 上下文参数。

在 web.xml 中添加这个

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>com.test.MyInitializer</param-value>
</context-param>

并定义你的初始化器

public class MyInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
    public void initialize(ConfigurableWebApplicationContext ctx) {
        PropertySource ps = new ResourcePropertySource(new ClassPathResource("sample.properties")); // handle exception
        ctx.getEnvironment().getPropertySources().addFirst(ps);
    }
}

参考:Spring 3.1 M1:统一的物业管理

于 2014-05-28T00:09:28.940 回答