Java env.getProperty不工作Spring PropertyPlaceHolderConfigure

Java env.getProperty不工作Spring PropertyPlaceHolderConfigure,java,spring,spring-4,Java,Spring,Spring 4,我正在使用spring加载属性文件 <bean id="appProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:/sample.properties" /> <property name="ignoreUn

我正在使用spring加载属性文件

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

propertyplaceholderconfigure
不会将其
位置的属性添加到
环境中。有了Java配置,您可以使用
@PropertySource
来实现这一点。

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

使用ApplicationContextInitializer接口及其配套的contextInitializerClasses servlet上下文参数

将其添加到web.xml中

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

上下文初始化类
com.test.MyInitializer
并定义初始值设定项

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);
    }
}
公共类MyInitializer实现ApplicationContextInitializer{
公共无效初始化(ConfigurableWebApplicationContext ctx){
PropertySource ps=new ResourcePropertySource(new ClassPathResource(“sample.properties”);//处理异常
ctx.getEnvironment().getPropertySources().addFirst(ps);
}
}

参考资料:

在Spring4中,通过xml还有什么可以做的吗?@invariant我不知道通过声明bean就可以做到这一点。您可以创建自己的
ApplicationContextAware
bean来添加它们。
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);
    }
}