在spring JavaConfig中,我可以定义属性源并注入到环境中
@PropertySource("classpath:application.properties")
@Inject private Environment environment;
如果是在xml中,我该如何做?我在JavaConfig类@ImportResource上使用context:property-placeholder来导入xml.但我无法使用environment.getProperty("xx")检索属性文件中定义的属性
<context:property-placeholder location="classpath:application.properties" />
发布于 2012-12-07 00:03:31
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并从(Web)ApplicationContext
获取ConfigurableEnvironment
即可。然后,只需向MutablePropertySources
添加一个PropertiesPropertySource
发布于 2016-11-14 07:17:32
如果您需要的只是访问文件"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>
https://stackoverflow.com/questions/13738623
复制相似问题