如果集合中有依賴對象,則可以使用 list , set 中的 ref 元素來注入這些信息。 或 Map。
在此示例中,我們以"論壇"為例,其中 一個問題可以有多個答案。但是Answer具有自己的信息,例如answerId,answer和postedBy。在此示例中使用了四個頁面:
Question.java Answer.java applicationContext.xml Test.java
在此示例中,我們使用的列表可以包含重復(fù)的元素,您可以使用僅包含唯一元素的set。但是,您需要更改在applicationContext.xml文件中設(shè)置的列表和在Question.java文件中設(shè)置的列表。
Question.java
此類包含三個屬性,兩個構(gòu)造函數(shù)和顯示信息的displayInfo()方法。在這里,我們使用列表來包含多個答案。
package com.nhooo; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<Answer> answers; public Question() {} public Question(int id, String name, List<Answer> 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<Answer> itr=answers.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
Answer.java
此類具有三個屬性id,name和by構(gòu)造函數(shù)和toString()方法。
package com.nhooo; public class Answer { private int id; private String name; private String by; public Answer() {} public Answer(int id, String name, String by) { super(); this.id = id; this.name = name; this.by = by; } public String toString(){ return id+" "+name+" "+by; } }
applicationContext.xml
ref 元素用于定義另一個bean的引用。在這里,我們使用 ref 元素的 bean 屬性來指定另一個bean的引用。
<?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="ans1" class="com.nhooo.Answer"> <constructor-arg value="1"></constructor-arg> <constructor-arg value="Java is a programming language"></constructor-arg> <constructor-arg value="John"></constructor-arg> </bean> <bean id="ans2" class="com.nhooo.Answer"> <constructor-arg value="2"></constructor-arg> <constructor-arg value="Java is a Platform"></constructor-arg> <constructor-arg value="Ravi"></constructor-arg> </bean> <bean id="q" class="com.nhooo.Question"> <constructor-arg value="111"></constructor-arg> <constructor-arg value="What is java?"></constructor-arg> <constructor-arg> <list> <ref bean="ans1"/> <ref bean="ans2"/> </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(); } }