Spring教程-使用Map的构造函数注入示例

使用Map的构造函数注入示例
在这个示例中,我们使用map作为包含回答和回答发布者的答案。在这里,我们同时使用键值对作为字符串。
和之前的示例一样,这是一个论坛的示例,其中一个问题可以有多个答案。
Question.java
这个类包含三个属性,两个构造函数和一个displayInfo()方法来显示信息。
package cn.javatiku;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<String, String> answers;
public Question() {}
public Question(int id, String name, Map<String, String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo() {
System.out.println("question id: " + id);
System.out.println("question name: " + name);
System.out.println("Answers....");
Set<Entry<String, String>> set = answers.entrySet();
Iterator<Entry<String, String>> itr = set.iterator();
while (itr.hasNext()) {
Entry<String, String> entry = itr.next();
System.out.println("Answer: " + entry.getKey() + " Posted By: " + entry.getValue());
}
}
}
applicationContext.xml
在这个XML文件中,我们使用map的entry属性来定义键和值信息。
<?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">
<bean id="q" class="cn.javatiku.Question">
<constructor-arg value="11"></constructor-arg>
<constructor-arg value="What is Java?"></constructor-arg>
<constructor-arg>
<map>
<entry key="Java is a Programming Language" value="Ajay Kumar"></entry>
<entry key="Java is a Platform" value="John Smith"></entry>
<entry key="Java is an Island" value="Raj Kumar"></entry>
</map>
</constructor-arg>
</bean>
</beans>
Test.java
这个类从applicationContext.xml文件中获取bean,并调用displayInfo()方法。
package cn.javatiku;
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 r = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(r);
Question q = (Question) factory.getBean("q");
q.displayInfo();
}
}
当你运行Test
类时,它将创建一个ID为11,问题为"What is Java?"的Question
对象,并且它包含一个map,其中包含了三个键值对,分别为"Java is a Programming Language"、"Java is a Platform"和"Java is an Island",值分别为"Ajay Kumar"、"John Smith"和"Raj Kumar"。然后,displayInfo()
方法将打印这些信息。