java 如何使用 Spring 创建 HashMap bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37901982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:55:52  来源:igfitidea点击:

How do I create a HashMap bean using Spring

javaspring

提问by Ahmad

I'm new to using Spring with Java and I'm trying to instantiate a simple HashMap using Spring's configuration file. I want to know what to put in the Spring config context file to make this work. I know util:mapis somehow used, but all the example codes I'm seeing are either complex instantiations (e.g. for HashMap<Class<?>,List<String>>) from which understanding is difficult, or the author hasn't explained well what he/she has done, leaving me frustrated!

我是将 Spring 与 Java 结合使用的新手,我正在尝试使用 Spring 的配置文件实例化一个简单的 HashMap。我想知道在 Spring 配置上下文文件中放入什么来完成这项工作。我知道util:map以某种方式使用了,但是我看到的所有示例代码要么是复杂的实例化(例如 for HashMap<Class<?>,List<String>>),从中很难理解,要么作者没有很好地解释他/她所做的事情,让我感到沮丧!

What do I need to put in my beans.xml context file if I want to generate a simple HashMap of this specification ? ...

如果我想生成这个规范的简单 HashMap,我需要在我的 beans.xml 上下文文件中放入什么?...

HashMap<Integer, String>

Please show a clear example showing the XML and stating any naming assumptions you're making.

请展示一个清晰的示例,显示 XML 并说明您所做的任何命名假设。

回答by Ryan Pelletier

I am using Spring 4.0.3, you can use this configuration.You can see the key type of the map is Integer, while the value type is String.

我用的是Spring 4.0.3,可以用这个配置。可以看到map的key类型是Integer,value类型是String。

<bean id="map" class="java.util.HashMap" scope="prototype" >
    <constructor-arg>
        <map key-type="java.lang.Integer" value-type="java.lang.String">
            <entry key="1" value="one" />
            <entry key="2" value="two" />
        </map>
    </constructor-arg>
</bean>

An example of getting this bean is the following.

获取此 bean 的示例如下。

public static void main(String[] args){

    ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

    Map<Integer,String> map = (HashMap) context.getBean("map");
    System.out.println(map);
}`