Open In App

Spring – Setter Injection with Map

Last Updated : 28 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring is an open-source lightweight framework that allows Java EE developers to build simple, reliable, and scalable enterprise applications. This framework is designed on the concept of Dependency Injection that focuses on providing various ways to manage business objects.

Dependency Injection

Dependency injection (DI) is a process where the objects define their dependencies i.e., the other objects they work with. It happens only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. Then the container is responsible to inject those dependencies when it creates the bean. This process is fundamentally the inverse, hence also called Inversion of Control (IoC).

Dependency injection exists in two ways, 

1) Constructor-based dependency injection – This is done by the container invoking a constructor with a number of arguments, each representing a dependency. We need to use <constructor-arg> sub-element of <bean> tag for constructor injection.

XML




<bean id="beanId" class="BeanClass">
  <constructor-arg type="String" value="test"/>
  <constructor-arg type="int" value="1002"/>
</bean>


2) Setter-based dependency injection –  This is done by the container calling setter methods on beans after invoking a no-argument constructor or no-argument static factory method to instantiate the bean. We need to use <property> sub-element of <bean> tag for setter injection.

XML




<bean id="beanId" class="BeanClass">
  <property name="secondBean" ref="SecondBean"/>
  <property name="message" value="This is message."/>
</bean>


Through setter injection using <property> tag, we can provide values like Strings, Primitives, Collections, etc. based on our requirement. In this example, we will see setter injection using Map. While we are using the map, we need to use <map> and <entry> tags to set the values to it.

XML




<bean id="beanId" class="BeanClass">
        <property name="name" value="geeks" />
        <property name="name2">
            <map>
                <entry key="key1" value="value1"/>
                <entry key ="key2" value-ref="DataSource"/>
            </map>
        </property>
</bean>


Example Project

We will create a simple Spring application in eclipse to display Name, Welcome Message, and Framework details as the output in the console.

Project Structure:

  • Create a new Java project – SpringSetterInjection.
  • Add all the required Spring Jar files to the project.
  • Create a bean class – InfoBean.java, to define all the properties and getter/setter methods of those properties.
  • Create XML configuration file – applicationContext.xml, for the bean configurations.
  • Create bean test class – InfoBeanTest.java, to define the application context container and get the bean objects.
  • Run the application to get the output.

After creating the project, bean classes, and the XML configuration file, below will be the project structure.

Project Structure

Project Structure

The spring jar files can be downloaded from Maven Repository.

Files to be created:

InfoBean.java:

Java




package com.geeks.beans;
  
import java.util.Map;
  
public class InfoBean {
      
    private String name;
    private String msg;
    private Map<String, String> frameworks;
      
      
    public Map<String, String> getFrameworks() {
        return frameworks;
    }
    public void setFrameworks(Map<String, String> frameworks) {
        this.frameworks = frameworks;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
      
    public void display() {
        System.out.println("Hi "+name+", "+msg);
        System.out.println("Framework Names: Description");
        for (Map.Entry<String,String> entry : frameworks.entrySet())
            System.out.println(entry.getKey() + ": " + entry.getValue());
    }
  
}


  • In the bean class, we defined properties ‘name’ and ‘msg’ as String type and ‘frameworks’ as Map.
  • Generate the getter/setter methods of all the properties.
  • Define a method – display(), to print the values of the properties.
  • As the field ‘framework’ is a type map, we need to iterate the map to print the key values.
  • So, here we are using a for-each loop to iterate the ‘frameworks’ and print the values in it.

applicationContext.xml:

XML




<?xml version="1.0" encoding="UTF-8"?>
  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
  
    <bean id="info" class="com.geeks.beans.InfoBean">
        <property name="name" value="Lakshmi" />
        <property name="msg" value="Welcome to GeeksforGeeks!!" />
        <property name="frameworks">
            <map>
                <entry key="Struts"
                    value="Struts is an open source framework used to develop Java MVC based web applications."></entry>
                <entry key="Spring"
                    value="Spring is an application framework used to develop Java Enterprise applications
                           and designed on concept called Dependency injection."></entry>
                <entry key="Hibernate"
                    value="Hibernate is an object-relational mapping (ORM) framework that works with relational
                           databases to manage the data."></entry>
            </map>
        </property>
    </bean>
  
</beans>


  • In the XML file, we need to include the bean XML schema location for the configuration.
  • We are setting the property values of Map using <map> and <entry key=”” value=””> tags inside the <property> tag.

InfoBeanTest.java:

Java




package com.geeks.test;
  
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
import com.geeks.beans.InfoBean;
  
public class InfoBeanTest {
  
    public static void main(String[] args) {
  
        ApplicationContext con = new ClassPathXmlApplicationContext("com/geeks/resources/applicationContext.xml");
        InfoBean infoBean = (InfoBean) con.getBean("info");
        infoBean.display();
    }
  
}


The application context container creates the bean object and we are getting that bean object to call the display() method.

Output:

  • Run the test class as a Java project.
  • The Spring container will create the ‘InfoBean’ object and it sets all the property values and make the bean object available to the developer.
  • Using the bean object, it calls the display() method and prints the below output in the console.
Output

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads