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

コンストラクタ注入とMapの例

この例では、 map 既に公開されたユーザー名の答えを持つ答えとして使用されます。ここでは、キーと値のペアをすべて文字列として使用します。

前の例と同様に、これはフォーラムの例であり、 一つの質問には複数の答えがあります。

Question.java

このクラスには3つの属性、2つのコンストラクタ、および情報を表示する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("question id:\"}+id);
    System.out.println("question name:\"+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()+" Posted By:"+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();
}
}