2

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:map is 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!

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

HashMap<Integer, String>

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

Ahmad
  • 12,886
  • 30
  • 93
  • 146
  • 1
    [Related question](http://stackoverflow.com/questions/5348310/how-to-inject-a-mapstring-list-in-java-springs) – augray Jun 18 '16 at 22:21

1 Answers1

7

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.

<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.

public static void main(String[] args){

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

    Map<Integer,String> map = (HashMap) context.getBean("map");
    System.out.println(map);
}`
Ryan Pelletier
  • 616
  • 7
  • 20
  • Thanks. Can you tell me what the following two lines do, and are they really needed ?: `` `` – Ahmad Jun 20 '16 at 16:33
  • They put initial values into the map, you do not need them. – Ryan Pelletier Jun 20 '16 at 17:06
  • 3
    It's definitely worth noting that the scope="prototype" is important here as java.util.HashMap is not threadsafe. This scope will cause a new map to be created for each request for this bean id. This is necessary because you typically don't want two beans using the same map for thread safety reasons. – java-addict301 Oct 11 '17 at 15:18
  • Plus +1 for adding scope="prototype". This is important, as I explained in my earlier response post. – java-addict301 Oct 11 '17 at 15:20