19

在 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" />
4

2 回答 2

7

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

这很简单,只需使用一个ApplicationContextAwarebean 并ConfigurableEnvironment(Web)ApplicationContext. 然后只需添加PropertiesPropertySource一个MutablePropertySources

于 2012-12-06T16:03:31.413 回答
-1

如果您只需要访问文件“application.properties”的属性“xx”,则无需 Java 代码即可通过在 xml 文件中声明以下 bean 来实现:

<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>
于 2016-11-13T23:17:32.393 回答