English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
의존 객체가 존재하는 경우, Setter 주입(관련 객체를 가진) 예제를 사용할 수 있습니다. list ، set 중 ref 요소를 사용하여 이러한 정보를 주입합니다. 또는 Map。 여기서는 property 요소 내에서 list, set 또는 map 요소를 사용합니다.
이 예제에서는 포럼을 예로 들었습니다, 그 중 한 개의 질문은 여러 답변을 가질 수 있습니다。 그러나 Answer는 자신의 정보를 가지고 있으며, 예를 들어 answerId, answer 및 postedBy입니다. 이 예제에서는 네 개의 페이지를 사용했습니다:
Question.java Answer.java applicationContext.xml Test.java
이 예제에서 사용하는 목록은 중복 요소를 포함할 수 있으며, 유일한 요소만 포함하는 set을 사용할 수 있습니다. 그러나 applicationContext.xml 파일에서 설정한 목록과 Question.java 파일에서 설정한 목록을 변경해야 합니다.
Question.java
이 클래스는 세 가지 속성, 두 개의 생성자 및 정보를 표시하는 displayInfo() 메서드를 포함하고 있습니다. 여기서는 여러 답변을 포함하는 목록을 사용합니다.
package com.w3codebox; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<Answer> answers; //setter와 getter 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 생성자와 toString() 메서드를 가지고 있습니다。
package com.w3codebox; public class Answer { private int id; private String name; private String by; //setter와 getter 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="answer1" class="com.w3codebox.Answer"> <property name="id" value="1></property> <property name="name" value="Java is a programming language"></property> <property name="by" value="Ravi Malik"></property> </bean> <bean id="answer2" class="com.w3codebox.Answer"> <property name="id" value="2></property> <property name="name" value="Java is a platform"></property> <property name="by" value="Sachin"></property> </bean> <bean id="q" class="com.w3codebox.Question"> <property name="id" value="1></property> <property name="name" value="What is Java?"></property> <property name="answers"> <list> <ref bean="answer1"/> <ref bean="answer2"/> </list> </property> </bean> </beans>
Test.java
이 클래스는 applicationContext.xml 파일에서 Bean을 가져와 displayInfo 메서드를 호출합니다.
package com.w3codebox; 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(); } }