English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 예제에서는
map
게시된 사용자 이름을 답변으로 가진 답변으로 사용됩니다. 여기서는 키와 값 쌍을 모두 문자열로 사용합니다.
이전 예제와 같이, 이는 포럼의 예제로서,
한 개의 질문에는 여러 가지 답변이 있을 수 있습니다
。
Question.java
이 클래스는 세 가지 속성, 두 개의 생성자 및 정보를 표시하는 displayInfo() 메서드를 포함하고 있습니다.
package com.w3codebox; 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("질문 id:"+id); System.out.println("질문 이름:"+name); System.out.println("답변들...."); 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("답변:"+entry.getKey()+" 게시자:"+entry.getValue()); } } }
applicationContext.xml
map
의
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="q" class="com.w3codebox.Question"> <constructor-arg value="11></constructor-arg> <constructor-arg value="What is Java?"></constructor-arg> <constructor-arg> <map> <entry key="Java is a Programming Language" value="Ajay Kumar"></entry> <entry key="Java is a Platform" value="John Smith"></entry> <entry key="Java is an Island" value="Raj Kumar"></entry> </map> </constructor-arg> </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(); } }