Define Spring @PropertySource in xml and use it in Environment

…衆ロ難τιáo~ 提交于 2019-12-02 22:46:39

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

If what you need is just access the property "xx" of the file "application.properties", you can accomplish that without Java code by declaring the following bean in your xml file:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="application.properties"/>
</bean>

Then if you want to inject the property in a bean just reference it as a variable:

<bean id="myBean" class="foo.bar.MyClass">
        <property name="myProperty" value="${xx}"/>
</bean>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!