7

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
invariant
  • 8,758
  • 9
  • 47
  • 61

2 Answers2

4

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

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

invariant
  • 8,758
  • 9
  • 47
  • 61