Define Spring @PropertySource in xml and use it in Environment

surajz picture surajz · Dec 6, 2012 · Viewed 15.8k times · Source

In spring JavaConfig, I can define property source and inject into Environment

@PropertySource("classpath:application.properties")

@Inject private Environment environment;

How do I do that if in xml? I am using context:property-placeholder, and on the JavaConfig class @ImportResource to import the xml. But I cannot retrieve property defined in the properties file using environment.getProperty("xx")

<context:property-placeholder location="classpath:application.properties" />

Answer

ElderMael picture ElderMael · Dec 6, 2012

AFAIK, there is no way of doing this by pure XML. Anyways, here is a little code I did this morning:

First, the test:

public class EnvironmentTests {

    @Test
    public void addPropertiesToEnvironmentTest() {

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "testContext.xml");

        Environment environment = context.getEnvironment();

        String world = environment.getProperty("hello");

        assertNotNull(world);

        assertEquals("world", world);

        System.out.println("Hello " + world);

    }

}

Then the class:

public class PropertySourcesAdderBean implements InitializingBean,
        ApplicationContextAware {

    private Properties properties;

    private ApplicationContext applicationContext;

    public PropertySourcesAdderBean() {

    }

    public void afterPropertiesSet() throws Exception {

    PropertiesPropertySource propertySource = new PropertiesPropertySource(
            "helloWorldProps", this.properties);

    ConfigurableEnvironment environment = (ConfigurableEnvironment) this.applicationContext
            .getEnvironment();

    environment.getPropertySources().addFirst(propertySource);

    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {

        this.applicationContext = applicationContext;

    }

}

And the testContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

    <util:properties id="props" location="classpath:props.properties" />

    <bean id="propertySources" class="org.mael.stackoverflow.testing.PropertySourcesAdderBean">
        <property name="properties" ref="props" />
    </bean>


</beans>

And the props.properties file:

hello=world

It is pretty simple, just use a ApplicationContextAware bean and get the ConfigurableEnvironment from the (Web)ApplicationContext. Then just add a PropertiesPropertySource to the MutablePropertySources