spring Constructor构造函数注入中有一个spring map注入,它表示一个类的构造函数参数中有Map类型的参数,和spring list参数差不多,所有的参数和基本类型的参数差不多,都是放在<constructor-arg>标签内部,只是比基本类型的参数多了一个<map>标签。
1:下面将做一个案例,在question.java问题类中有一个构造函数,里面有一个map参数,如下:
package com.tpyyes; 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); 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文件向Question(int id, String name, Map<String, String> answers)这个构造函数中注入参数值,map参数的每个key与value值都放在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="que" class="com.javatpoint.Question"> <constructor-arg value="11"></constructor-arg> <constructor-arg value="What is Java?"></constructor-arg> <constructor-arg> <map> <entry key="Java是一门语言" value="回答者为张三"></entry> <entry key="Java是一个组件" value="回答者为李四"></entry> <entry key="Java是一种咖啡" value="回答者王五"></entry> </map> </constructor-arg> </bean> </beans>
3:在Test.java类中初始化applicationContext.xml,这样就会将设置的值注入到question类中的构造函数内,然后调用displayInfo()输出我们注入的值,代码如下:
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("que"); q.displayInfo(); } }
完毕!