Spring中的地图用法

时间:2016-04-05 23:54:55

标签: java spring collections

Various() forms_of_writing = _andNaming( IDENTIFIERS )

我正在尝试在Spring中实现Collections的依赖注入。该程序给出错误。我无法弄清楚错误。

1 个答案:

答案 0 :(得分:0)

package com.abc

import java.util.Map;

public class CoffeeShopMap {
    private Map<Integer, String> waiters;

    //Getter and Setter of Map waiters

    public Map<Integer, String> getWaiters() {
        return waiters;
    }

    public void setWaiters(Map<Integer, String> waiters) {
        this.waiters = waiters;
    }

    public void mapExample() {
        for (Map.Entry<Integer, String> e : waiters.entrySet()) {
            Integer key = e.getKey();
            String value = e.getValue();
            System.out.println(key + " : " + value);

        }
    }
}

package com.abc
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CoffeeShopTest {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("WaiterMap.xml");
        CoffeeShopMap shop = (CoffeeShopMap) context.getBean("w");
        shop.mapExample();
    }
}

//XML file named WaiterMap.xml
<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">

    <bean id="w" class="com.abc.CoffeeShopMap">
        <property name="waiters">
            <map>
                <entry key="1" value="Michael" />
                <entry key="2" value="Peter" />
                <entry key="3" value="Raj" />
            </map>
        </property>
    </bean>


</beans>