Constructor Injection with Map Example in Spring

In this case, we are utilizing guide map as the answer that have answer with posted username. Here, we are utilizing key and worth pair both as a string. Like past samples, it is the illustration of gathering where one inquiry can have numerous answers.

You can learn previous examples, it is the example of forum where one question can have multiple answers.

This class contains three properties, two constructors and displayInfo() method to display the information.

package com.javatportal;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class Question {
private int id;
private String name;
private Map<String,String> answers;

public Question() {}
public Question(int id, String name, Map<String, String> answers) {
	super(); = id; = name;
	this.answers = answers;

public void displayInfo(){
	System.out.println("question id:"+id);
	System.out.println("question name:"+name);
	Set<Entry<String, String>> set=answers.entrySet();
	Iterator<Entry<String, String>> itr=set.iterator();
		System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());


The entry attribute of map is used to define the key and value information.

<?xml version="1.0" encoding="UTF-8"?>

<bean id="q" class="com.javatportal.Question">
<constructor-arg value="11"></constructor-arg>
<constructor-arg value="What is Java?"></constructor-arg>
<entry key="Java is a Programming Language"  value="Ajay Kumar"></entry>
<entry key="Java is a Platform" value="John Smith"></entry>
<entry key="Java is an Island" value="Raj Kumar"></entry>


This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.

package com.javatportal;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class Test {
public static void main(String[] args) {
	Resource r=new ClassPathResource("applicationContext.xml");
	BeanFactory factory=new XmlBeanFactory(r);
	Question q=(Question)factory.getBean("q");