Setter Injection with Map

  • A map contains values based on the key i.e. key and value pair. Each pair is known as an entry. Map contains only unique elements.
  • The Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.
  • Actually In spring, we use Map.Entry class object only

Now we will see a program to understand the concept of setter injection with map.

Required Files:

  1. Customer.java
  2. springConfig.xml
  3. Test.java

Customer.java

package java8s;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Customer {
    private Map data;
    public void setData(Map data) {
        this.data = data;
    }
    public void print() {
        Set s = data.entrySet();
        Iterator itr = s.iterator();
        while (itr.hasNext()) {
            Map.Entry m = (Map.Entry) itr.next();
            System.out.println(m.getKey() + " --- " + m.getValue());
        }
    }
}

springConfig.xml

<< ? xml version = "1.0"
encoding = "UTF-8" ? >
    <
    beans
xmlns = "http://www.springframework.org/schema/beans"
xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns: p = "http://www.springframework.org/schema/p"
xsi: schemaLocation = "http://www.springframework.org/schema/beans
http: //www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <
    beans >
    <
    bean id = "id3"
class = "java8s.Customer" >
    <
    property name = "data" >
    <
    map >
    <
    entry key = "k101" >
    <
    value > 350 < /entry> <
    entry key = "k102" >
    <
    value > java8s < /value> <
    /entry> <
    entry key = "k103" >
    <
    value > 123.456 < /value> <
    /entry> <
    /map> <
    /property> <
    /bean> <
    /beans>

Test.java

Package java8s;
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;
public class Test {
    public static void main(String[] args) {
        Resource resource = new ClassPathResource("springConfig.xml");
        BeanFactory bf = new XmlBeanFactory(resource);
        Customer c = (Customer) bf.getBean("id3");
        c.print();
    }
}

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment