English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

setter 주입과 Map 예제를 사용합니다

이 예제에서는 map 질문의 답변으로서, 이 질문의 답변은 키이고, 사용자 이름은 값으로 사용됩니다. 여기서는 키와 값 쌍을 모두 문자열로 사용합니다.

이전 예제와 같이, 이는 포럼의 예제로서, 하나의 질문에는 여러 개의 답변이 있을 수 있습니다

Question.java

이 클래스는 세 가지 속성을 포함하고 있으며, getters와 setters와 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;
//getters and setters
public void displayInfo(){
    System.out.println("questionid:")+id);
    System.out.println("questionname:")+name);
    System.out.println("Answers....");
    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()+"PostedBy:"+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>
<property name="id" value="1></property>
<property name="name" value="WhatisJava?"></property>
<property name="answers">
<map>
<entry key="Java는프로그래밍언어" value="SonooJaiswal"></entry>
<entry key="Java는플랫폼" value="SachinYadav"></entry>
</map>
</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();
    
}
}