env.getProperty not working Spring PropertyPlaceholderConfigurer

纵然是瞬间 提交于 2019-12-01 04:55:30

问题


I am loading properties file using 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.

but when i am trying to get using env

@Resource
 private Environment environment;

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

回答1:


A PropertyPlaceholderConfigurer does not add the properties from its locations to the Environment. With Java config, you can use @PropertySource to do that.




回答2:


If any one want to achieve this without using @PropertySource

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

add this in 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



来源:https://stackoverflow.com/questions/23895908/env-getproperty-not-working-spring-propertyplaceholderconfigurer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!