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" > <property name="properties" ref="props" /> </bean></beans>
和props.properties文件:
hello=world
这是很简单,只需使用一个
ApplicationContextAwarebean并获得
ConfigurableEnvironment从
(Web)ApplicationContext。然后只需
PropertiesPropertySource在
MutablePropertySources



