surajz surajz - 4 months ago 32
Java Question

Define Spring @PropertySource in xml and use it in Environment

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


@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="" />


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 {

    public void addPropertiesToEnvironmentTest() {

        ApplicationContext context = new ClassPathXmlApplicationContext(

        Environment environment = context.getEnvironment();

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


        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(

    ConfigurableEnvironment environment = (ConfigurableEnvironment) this.applicationContext



    public Properties getProperties() {
        return properties;

    public void setProperties(Properties 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="" />

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


And the file:


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