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

1.pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.practice</groupId>
<artifactId>InjectListDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>


</dependencies>
</project>

2.Writing Spring Beans

In This Example Im Writting one Spring Beans Named With University

University.java

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;
}

@Override
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).

applicationContext.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-4.3.xsd">
<bean id="university" class="com.practice.University">
<property name="professors">
<map>
<entry key = "1" value = "B"> </entry>
<entry key = "2" value = "D"></entry>
<entry key= "3" value = "welcome to javalschool"></entry>
</map>
</property>
</bean>
</beans>

4.Now Create Test class ,RunThe Code

AppTest.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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");
System.out.println(university.toString());

}

}

output:

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

No comments:

Post a Comment