env.getProperty not working Spring PropertyPlaceho

2019-02-18 04:22发布

问题:

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