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>
Java类
public class TestBean{
@Resource(name = "queueProperties")
private Properties queueProperties;
getPropertyValue(){
queueProperties.getProperty("queueURL");
}
}
在此处输入代码
web.xml .... 上下文配置位置 /WEB-INF/ApplicationContext.xml
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
...
在调试代码时注意到 Properties obj 未注入(inject)并显示为 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"/>
如果您有多个属性文件,请参阅此 How to Configure more than one properties file在 Spring 3 中。
另一种方法:
配置一个扩展类 PropertyPlaceholderConfigurer
的 bean/类并重写 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");
关于java - 在 Spring Context 的帮助下使用注释 @Resource 读取属性时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644667/