【问题标题】:Unable to load values of HashMap from Spring XML无法从 Spring XML 加载 HashMap 的值
【发布时间】:2017-03-24 21:03:08
【问题描述】:

我已经为 hashmap 编写了一个 xml 文件。
有两个问题,xml 文件显示一个红叉,但是当鼠标指针悬停在它上面或在“问题”部分时,都没有出现错误消息。
第二个问题是,它编译得很好,但是值键值不会传输到 hashmap 对象。类中的 HashMap 对象保持为“空”

哈希映射的 XML 是:

<bean id="GateKeeper" class="com.smarttrade.domain.GateKeeper"/>

<bean id="ClientToRateMap" class="java.util.HashMap">
    <constructor-arg>
        <map key-type="java.lang.String" value-type="java.lang.Integer">
            <entry key="A" value=1 />
            <entry key="B" value=2 />
            <entry key="C" value=3 />
            <entry key="D" value=4 />
        </map>
    </constructor-arg>
</bean>

类是

public class GateKeeper {

    @Resource
    @Qualifier("ClientToRateMap")
    HashMap<String, Integer> ClientToRateMap;

    public void ApplyRateLimitPerClient(ClientRequestEntity client) {
        System.out.println(ClientToRateMap);     // Ouput is NULL
    }
}

【问题讨论】:

    标签: java xml spring spring-boot hashmap


    【解决方案1】:

    很可能地图已创建,但未注入,因为您的 xml 中没有 &lt;annotation-config/&gt;

    【讨论】:

      【解决方案2】:

      要解决您的代码的两个问题,请按照以下步骤操作:

      (1)需要在xml中定义spring命名空间,如下图:

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="
             http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      
      <!-- add your beans here -->
      
      </beans>
      

      (2) 为了让容器找到你的bean,你需要用@Component标记你的GateKeeper

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多