一尘不染

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

java

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

阅读 542

收藏
2020-12-03

共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

这是很简单,只需使用一个ApplicationContextAwarebean并获得ConfigurableEnvironment(Web)ApplicationContext。然后只需PropertiesPropertySourceMutablePropertySources

2020-12-03