How To Inject Map Into Spring Bean With Example

In This Article We will Learn How To Inject Map into the spring bean.

Tools Used In This Article

  • Spring 4.3.2
  • Maven 4.0.0
  • JDK 1.7

Project Directory Structure

Maven Dependencies

Add The Following Dependencies to the pom.xml

  • spring-core
  • spring-beans
  • spring-context


<project xmlns="" xmlns:xsi=""





2.Writing Spring Beans

In This Example Im Writting one Spring Beans Named With University

package com.practice;

import java.util.Map;

public class University {
private Map professors;

public Map getProfessors() {
return professors;

public void setProfessors(Map professors) {
this.professors = professors;

public String toString() {
return "University [professors=" + professors + "]";


3.Setting Up Spring Configuration File

To Inject java.util.Map Into Spring Bean we need to use <map> tag and <entry> tag and key and value attributesin spring configuration File(applicationContext.xml).


<beans xmlns=""
<bean id="university" class="com.practice.University">
<property name="professors">
<entry key = "1" value = "B"> </entry>
<entry key = "2" value = "D"></entry>
<entry key= "3" value = "welcome to javalschool"></entry>

4.Now Create Test class ,RunThe Code

import org.springframework.context.ApplicationContext;

import com.practice.University;

public class AppTest {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
University university = (University)context.getBean("university");




University [professors={1=B, 2=D, 3=welcome to javalschool}]

No comments:

Post a Comment