The Wayback Machine - https://web.archive.org/web/20240906181753/https://www.geeksforgeeks.org/spring-setter-injection-with-non-string-map/
Open In App

Spring – Setter Injection with Non-String Map

Last Updated : 11 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is used to set DI as SDI in the bean. For this, the property to be set with the SDI is declared under the <property> tag in the bean-config file. A Collection in java is a group of individual objects. Spring framework provides us facility of Setter injection using the following Collections:

Implementation

The map will have both key and value as non-strings. Key will be Employee which has the following fields:

  • Name
  • Employee ID
  • Department

Value will be Address which has the following parameters:

  • House No.
  • Pincode
  • State
  • Country

A. Company.java

A company has a list of employees.

Java




// Java Program to Illustrate Company Class
   
package com.geeksforgeeks.org;
   
// Importing required classes
import com.geeksforgeeks.org.Address;
import com.geeksforgeeks.org.Employee;
import java.util.*;
import java.util.Map.Entry;
   
// Class
public class Company {
   
    // Class member variable
    private Map<Employee, Address> employees;
   
    // Method
    public void display()
    {
        // Iterating over Map using for each loop
        for (Map.Entry<Employee, Address> entry :
             employees.entrySet()) {
   
            // Print statement
            System.out.println(
                "Employee Data ->"
                + entry.getKey().toString() + " Address ->"
                + entry.getValue().toString());
        }
    }
}


B. Employee.java

Java




// Java Program to Illustrate Employee Class
   
package com.geeksforgeeks.org;
   
// Importing required classes
import com.geeksforgeeks.org.Address;
   
// Class
public class Employee {
   
    // Class data members
    private String name;
    private String employeeID;
    private String department;
   
    public Employee(String name, String employeeID,
                    String department)
    {
        // This keyword refers to current instance itself
        this.name = name;
        this.employeeID = employeeID;
        this.department = department;
    }
   
    // Method
    // Overriding toString() method
    public String toString()
    {
        return ("[" + name + "," + employeeID + ","
                + department + "]");
    }
}


C. Address.java

Java




// Java Program to Illustrate Address Class
   
package com.geeksforgeeks.org;
   
// Class
public class Address {
   
    // Class data members
    private String houseNo;
    private String pincode;
    private String state;
    private String country;
   
    // Constructor
    public Address(String houseNo, String pincode,
                   String state, String country)
    {
        super();
        this.houseNo = houseNo;
        this.pincode = pincode;
        this.state = state;
        this.country = country;
    }
   
    // Method
    // Overriding toString() method
    public String toString()
    {
        return "[" + houseNo + "," + pincode + "," + state
            + "," + country + "]";
    }
}


D. applicationContext.xml

Configuration file for our project.

Java




<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
    
    <bean id="employee1" class="com.geeksforgeeks.org.Employee">  
      <property name="name" value="Sahil"></property>  
      <property name="employeeID" value="101"></property>  
      <property name="department" value="Game development"></property>  
    </bean>  
      <bean id="address1" class="com.geeksforgeeks.org.Address">  
      <property name="houseNo" value="2"></property>  
      <property name="pincode" value="110111"></property>  
      <property name="state" value="Bihar"></property>  
      <property name="country" value="India"></property>  
    </bean>  
  
    <bean id="company" class="com.geeksforgeeks.org.Company">  
      <map>  
      <entry key-ref="employee1" value-ref="address1"></entry>  
      </map>  
      </property>  
    </bean>  
    
</beans>


E. Test.java

Main file for running our project.

Java




// Java Program to Illustrate Application Class
   
package com.geeksforgeeks.org;
   
// importing required classes
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
   
// Application class
// Main class
public class Test {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Creating a class path resource
        Resource resource = new ClassPathResource(
            "applicationContext.xml");
   
        // Creating an object of Beanfactory class
        BeanFactory factory = new XmlBeanFactory(resource);
   
        // Creating an object of Employee class
        Company c = (Company)factory.getBean("company");
   
        // Calling print() method inside main() method
        c.display();
    }
}


Output:

Employee Data -> [Sahil, 101, Game development], Address -> [2, 110111, Bihar, India]


Previous Article
Next Article

Similar Reads

Spring - Setter Injection vs Constructor Injection
Spring Framework is built on top of servlets and one of its main features is Dependency Injection (DI) it's one of the most common principles of modern software development and it allows us to achieve the principle of Inversion Of Control (IoC) i.e. shifting the creation, management and the lifecycle of objects from the programmer to the framework.
7 min read
Spring - Setter Injection with Non-String Collection
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
3 min read
Spring - Setter Injection with Map
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 obje
5 min read
Spring - Injecting Literal Values By Setter Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
4 min read
Spring - Dependency Injection by Setter Method
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from objec
3 min read
Spring - Injecting Objects by Setter Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Setter Injection with Dependent Object
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
3 min read
Spring - Setter Injection with Collection
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters methods. A bean-configuration file is use
2 min read
Spring - Constructor Injection with Non-String Map
In the Constructor Injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean is done through the bean-configuration file. For this, the property to be set with the constructor dependency injection is declared under the &lt;constructor-arg
4 min read
Spring Dependency Injection: @Autowired vs Constructor Injection
In Spring framework, dependency injection is a key idea that lets you inject dependencies into a class in preference to hard coding them. This provides loose coupling and makes the code extra maintainable and testable. There are distinct methods to perform dependency injection. Common Approaches to Perform Dependency InjectionBelow is the list of
4 min read
Spring - Constructor Injection with Non-String Collection
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. In the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as cons
3 min read
Spring - Constructor Injection with Map
In the Constructor Injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the &lt;constructor-a
3 min read
Spring Boot - Dependency Injection and Spring Beans
Spring Boot is a powerful framework for building RESTful APIs and microservices with minimal configuration. Two fundamental concepts within Spring Boot are Dependency Injection (DI) and Spring Beans. Dependency Injection is a design pattern used to implement Inversion of Control (IoC), allowing the framework to manage object creation and dependenci
6 min read
Spring - Constructor Injection with Collection
In the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the &lt;constructor-a
2 min read
Spring - Difference Between Inversion of Control and Dependency Injection
Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and Applic
4 min read
Spring - Constructor Injection with Dependent Object
In the constructor injection, the dependency injection will be injected with the help of constructors. Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the bean-configuration file For this, the property to be set with the constructor dependency injection is declared under the &lt;constructor-a
3 min read
Spring - Injecting Objects By Constructor Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Injecting Literal Values By Constructor Injection
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
5 min read
Spring - Difference Between Dependency Injection and Factory Pattern
Dependency Injection and Factory Pattern are almost similar in the sense that they both follow the interface-driven programming approach and create the instance of classes. A. Factory Pattern In Factory Pattern, the client class is still responsible for getting the instance of products by class getInstance() method of factory class, which means the
4 min read
Spring - When to Use Factory Design Pattern Instead of Dependency Injection
Prerequisite: Factory Pattern vs Dependency Injection Factory Design Pattern and Dependency Injection Design both are used to define the interface-driven programs in order to create objects. Dependency Injection is used to obtain a loosely coupled design, whereas the Factory Pattern adds coupling, between objects, factories, and dependencies. In th
2 min read
Spring - When to Use @Qualifier and @Autowired For Dependency Injection
In the world of Spring Framework, managing dependencies is a fundamental aspect of building robust and maintainable applications. Spring offers two primary annotations to facilitate dependency injection: @Autowired and @Qualifier. Understanding when and how to use these annotations is crucial for effective bean wiring .@Autowired and @Qualifier are
6 min read
XML - Based Injection in Spring
In this article, we will be exploring XML-based Injection in Spring. and also creating a sample course management system using ApplicationContext that manages the complete lifecycle of a bean from its creation to destruction in a seamless manner. XML-based injectionXML-based injection refers to security vulnerabilities that can occur in Spring appl
4 min read
Spring - Dependency Injection with Factory Method
Spring framework provides Dependency Injection to remove the conventional dependency relationship between objects. To inject dependencies using the factory method, we will use two attributes factory-method and factory-bean of bean elements. Note: Factory methods are those methods that return the instance of the class. Factory Method: These are thos
8 min read
Spring Dependency Injection with Example
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from objec
8 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Advantages of getter and setter Over Public Fields in Java with Examples
Providing getter and setter methods to access any class field in Java can at first look pointless and meaningless, simply because you can make the field public, and it is available in Java programs from anywhere. In reality, many programmers do this in the early days, but once you start thinking in terms of enterprise application or production code
2 min read
How to Build a Simple Alarm Setter App in Android?
In this article, we are going to see how to build a much interesting app named Alarm Setter. Alarm plays a vital role in our day-to-day life. Nowadays alarm has become our wake-up assistant. Every mobile phone is associated with an alarm app. We will create this app using android studio. Android Studio provides a great unified environment to build
6 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Article Tags :
Practice Tags :