我們可以在Spring框架中通過構(gòu)造函數(shù)注入集合值。 constructor-arg 元素內(nèi)可以使用三個(gè)元素。
可以是: List Set Map
每個(gè)集合可以具有基于字符串和基于非字符串的值。 在此示例中,我們以"論壇"為例,其中 一個(gè)問題可以有多個(gè)答案。一共有三頁:
Question.java applicationContext.xml Test.java
在此示例中,我們使用的列表可以包含重復(fù)的元素,您可以使用僅包含唯一元素的set。但是,您需要更改在applicationContext.xml文件中設(shè)置的列表和在Question.java文件中設(shè)置的列表。
Question.java
此類包含三個(gè)屬性,兩個(gè)構(gòu)造函數(shù)和顯示信息的displayInfo()方法。在這里,我們使用列表來包含多個(gè)答案。
package com.nhooo; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<String> answers; public Question() {} public Question(int id, String name, List<String> answers) { super(); this.id = id; this.name = name; this.answers = answers; } public void displayInfo(){ System.out.println(id+" "+name); System.out.println("answers are:"); Iterator<String> itr=answers.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
applicationContext.xml
此處使用builder-arg的list元素定義列表。
<?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.nhooo.Question"> <constructor-arg value="111"></constructor-arg> <constructor-arg value="What is java?"></constructor-arg> <constructor-arg> <list> <value>Java is a programming language</value> <value>Java is a Platform</value> <value>Java is an Island of Indonasia</value> </list> </constructor-arg> </bean> </beans>
Test.java
此類從applicationContext.xml文件獲取Bean并調(diào)用displayInfo方法。
package com.nhooo; 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(); } }