Java env.getProperty 不工作 Spring PropertyPlaceholderConfigurer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23895908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:55:04  来源:igfitidea点击:

env.getProperty not working Spring PropertyPlaceholderConfigurer

javaspringspring-4

提问by invariant

I am loading properties file using spring

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

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

when i am getting property value using

当我使用

@Value("${testkey}")its working fine.

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

but when i am trying to get using env

但是当我尝试使用 env 时

@Resource
 private Environment environment;

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

采纳答案by Sotirios Delimanolis

A PropertyPlaceholderConfigurerdoes not add the properties from its locationsto the Environment. With Java config, you can use @PropertySourceto do that.

APropertyPlaceholderConfigurer不会将其属性添加locationsEnvironment. 使用 Java 配置,您可以使用它@PropertySource来做到这一点。

回答by invariant

If any one want to achieve this without using @PropertySource

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

use ApplicationContextInitializer interface and its companion, the contextInitializerClasses servlet context param.

使用 ApplicationContextInitializer 接口和它的伴侣,contextInitializerClasses servlet 上下文参数。

add this in web.xml

在 web.xml 中添加这个

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

and define your Initializer

并定义您的初始化程序

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);
    }
}

Reference : Spring 3.1 M1: Unified Property Management

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