在xml中定义Spring @PropertySource并在Environment中使用它

时间:2012-12-06 07:08:49

标签: java spring properties spring-environment

在Spring JavaConfig中,我可以定义属性源并注入到Environment

@PropertySource("classpath:application.properties")

@Inject private Environment environment;

如果在xml中我该怎么做? 我使用context:property-placeholder,并在JavaConfig类@ImportResource上导入xml。但我无法使用environment.getProperty(“xx”)

检索属性文件中定义的属性
<context:property-placeholder location="classpath:application.properties" />

2 个答案:

答案 0 :(得分:5)

AFAIK,纯XML无法做到这一点。无论如何,这是我今天早上做的一些代码:

首先,测试:

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);

    }

}

然后上课:

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;

    }

}

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>

props.properties文件:

hello=world

这很简单,只需使用ApplicationContextAware bean并从ConfigurableEnvironment获取(Web)ApplicationContext。然后只需向PropertiesPropertySource

添加MutablePropertySources即可

答案 1 :(得分:-1)

如果你需要的只是访问该物业&#34; xx&#34;在文件&#34; application.properties&#34;中,您可以通过在xml文件中声明以下bean来实现,而无需Java代码:

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

然后,如果要在bean中注入属性,只需将其作为变量引用:

<bean id="myBean" class="foo.bar.MyClass">
        <property name="myProperty" value="${xx}"/>
</bean>