java - 在 Spring Context 的帮助下使用注释 @Resource 读取属性时出现问题

标签 java spring

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/

相关文章:

来自匿名内部类内部的Java返回方法

java - Spring版本不兼容

java - Spring 集成: process files line by line persisting read state

java - 如何从属性文件配置 Hystrix 注释?

java - 找不到类路径的速度模板

java - Android 创建目录层次结构

java - java中基于条件的xpath

java - 如何使用 Hibernate 将 `null` 值插入数据库?

Spring JPA 存储库 Autowiring 问题

java - 在编写 Spring 集成测试时从 Spring 组件扫描中排除特定类