在 xml 中定义 Spring @PropertySource,并在环境中使用它

在春季JavaConfig中,我可以定义属性源并注入到环境中

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

答案 1

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

这很简单,只需使用一个豆子并从中获取.然后只需将一个添加到ApplicationContextAwareConfigurableEnvironment(Web)ApplicationContextPropertiesPropertySourceMutablePropertySources


答案 2

如果您只需要访问文件“application.properties”的属性“xx”,则可以通过在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>