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

Konstruktor-Einbau und Map-Beispiel

In diesem Beispiel verwenden wir map als Antwort mit veröffentlichtem Benutzernamen. Hier verwenden wir Schlüssel-Wert-Paare beide als Strings.

Wie im obigen Beispiel ist es ein Beispiel für ein Forum, wo Ein Problem kann mehrere Antworten haben

Question.java

Diese Klasse enthält drei Attribute, zwei Konstruktoren und die displayInfo()-Methode zum Anzeigen von Informationen.

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("Fragen-ID:")}+id);
    System.out.println("Fragenname:",+name);
    System.out.println("Antworten....");
    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("Antwort:",+entry.getKey()+" Geschrieben von:"+entry.getValue());
    }
}
}

applicationContext.xml

map von entry Das Attribut wird verwendet, um Schlüssel- und Wertinformationen zu definieren.

<?xml version="1.0" encoding="UTF-8"-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="Was ist Java?"></constructor-arg>
<constructor-arg>
<map>
<entry key="Java ist eine Programmiersprache" value="Ajay Kumar"></entry>
<entry key="Java ist eine Plattform" value="John Smith"></entry>
<entry key="Java ist eine Insel" value="Raj Kumar"></entry>
</map>
</constructor-arg>
</bean>
</beans>

Test.java

Diese Klasse ruft die Bean aus der Datei applicationContext.xml ab und ruft die displayInfo()-Methode auf.

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();
}
}