Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Setter Injection with Map


In this example, we are using map as the answer for a question that have answer as the key and username as the value. Here, we are using key and value pair both as a string.

Like previous examples, it is the example of forum where one question can have multiple answers.

Question.java

This class contains three properties, getters & setters and displayInfo() method to display the information.

  1. package com.Kreationnext;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.Set;
  5. import java.util.Map.Entry;
  6. public class Question {
  7. private int id;
  8. private String name;
  9. private Map<String,String> answers;
  10. //getters and setters
  11. public void displayInfo(){
  12.     System.out.println(“question id:”+id);
  13.     System.out.println(“question name:”+name);
  14.     System.out.println(“Answers….”);
  15.     Set<Entry<String, String>> set=answers.entrySet();
  16.     Iterator<Entry<String, String>> itr=set.iterator();
  17.     while(itr.hasNext()){
  18.         Entry<String,String> entry=itr.next();
  19.         System.out.println(“Answer:”+entry.getKey()+” Posted By:”+entry.getValue());
  20.     }
  21. }
  22. }

applicationContext.xml

The entry attribute of map is used to define the key and value information.

  1. <?xml version=“1.0” encoding=“UTF-8”?>
  2. <beans
  3.     xmlns=“http://www.springframework.org/schema/beans”
  4.     xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
  5.     xmlns:p=“http://www.springframework.org/schema/p”
  6.     xsi:schemaLocation=”http://www.springframework.org/schema/beans 
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”>
  8. <bean id=“q” class=“com.Kreationnext.Question”>
  9. <property name=“id” value=“1”></property>
  10. <property name=“name” value=“What is Java?”></property>
  11. <property name=“answers”>
  12. <map>
  13. <entry key=“Java is a programming language”  value=“Sonoo Jaiswal”></entry>
  14. <entry key=“Java is a Platform” value=“Sachin Yadav”></entry>
  15. </map>
  16. </property>
  17. </bean>
  18. </beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the displayInfo() method.

  1. package com.Kreationnext;
  2. import org.springframework.beans.factory.BeanFactory;
  3. import org.springframework.beans.factory.xml.XmlBeanFactory;
  4. import org.springframework.core.io.ClassPathResource;
  5. import org.springframework.core.io.Resource;
  6. public class Test {
  7. public static void main(String[] args) {
  8.     Resource r=new ClassPathResource(“applicationContext.xml”);
  9.     BeanFactory factory=new XmlBeanFactory(r);
  10.     Question q=(Question)factory.getBean(“q”);
  11.     q.displayInfo();
  12. }
  13. }

Comments

comments