spring map注入分为构造函数注入与set注入,之前有讲构造器注入map,现在就用set来注入map,他们之间的区别在于构造函数注入是将Map放在<constructor-arg>标签里面,而set注入是将Map放在<property>中,使用也非常的简单,如下。
1:Question.java问题类,里面有一个3个属性,代码如下。
package com.tpyyes.pojo; import java.util.Map; public class Question { private int id; private String name; private Map<String,String> answers; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getAnswers() { return answers; } public void setAnswers(Map<String, String> answers) { 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()); } } }
2:创建applicationContext.xml文件,在spring中对Map进行注入,代码如下:
<?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="com.tpyyes.Question"> <property name="id" value="1"></property> <property name="name" value="Java是什么东西?"></property> <property name="answers"> <map> <entry key="Java is编程语言" value="回答者是张三"></entry> <entry key="Java一种组件" value="回答者是李四"></entry> </map> </property> </bean> </beans>
3:在Test.java类中初始化applicationContext,通过map注入将数据注入到属性中,代码如下:
package com.tpyyes; 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(); } }
完毕!