ApplicationContext.xml
<beans>
....
<bean id="queueProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:queueCredentials.properties</value>
</list>
</property>
</bean>
</beans>
JavaClass
public class TestBean{
@Resource(name = "queueProperties")
private Properties queueProperties;
getPropertyValue(){
queueProperties.getProperty("queueURL");
}
}
在此处输入代码
web.xml。。。。contextConfigLocation/WEB-INF/ApplicationContext.xml
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
...
在调试代码时,注意到Properties obj没有被注入并显示为null,尝试了@Autowired和@Qualifier("queueProperties"(,但没有成功。
Spring 3您可以通过直接读取属性
@Value("${propertyName}")
private String propertyField;
属性可以通过XML进行配置,如下所示:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:queueCredentials.properties" id="propertyConfigurer"/>
如果您有多个属性文件,请参阅Spring 3中的How to Configure more one properties file。
另一种方法:
配置一个bean/class来扩展类PropertyPlaceholderConfigurer
并覆盖processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props)
方法以从文件中读取所有属性。
以下是示例:
public class PropertyReader extends PropertyPlaceholderConfigurer
{
private static Map<String, String> propertiesMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props)
{
try{
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
propertiesMap.put(keyStr,props.getProperty(keyStr));
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
public static String getProperty(String name) {
return propertiesMap.get(name);
}
}
XML配置:
<bean id="customerPropertyReader" class="PropertyReader">
<property name="location" value="classpath:queueCredentials.properties"/>
</bean>
您可以访问如下所示的任何属性:
String propValue = PropertyReader.getProperty("queueURL");