Env.getProperty not working Spring PropertyPlaceholderConfigurer

I am loading a 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 get the property value using

@Value("${testkey}") works fine.

but when i try to use env

@Resource
 private Environment environment;

environment.getProperty("testkey") // returning null
+4
source share
2 answers

A PropertyPlaceholderConfigurerdoes not add properties from locationsto Environment. With Java configuration you can use @PropertySourcefor this.

+3
source

If someone wants to achieve this without using @PropertySource

use the ApplicationContextInitializer interface and its satellite, the context context parameter contextInitializerClasses.

add this to 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);
    }
}

: Spring 3.1 M1:

+1

Source: https://habr.com/ru/post/1542218/


All Articles