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

Injection de constructeur et exemple de Map

Dans cet exemple, nous utilisons map les réponses sont des réponses d'utilisateurs publiés. Ici, nous utilisons les paires clé-valeur toutes en tant que chaînes.

Comme dans l'exemple précédent, c'est un exemple de forum, où Une question peut avoir plusieurs réponses

Question.java

Cette classe contient trois attributs, deux constructeurs et la méthode displayInfo() utilisée pour afficher les informations.

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 de la question : "+id);
    System.out.println("Nom de la question : "+name);
    System.out.println("Réponses....");
    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("Réponse : "+entry.getKey()+" Posté par :"+entry.getValue());
    }
}
}

applicationContext.xml

map du entrée Les propriétés sont utilisées pour définir les informations de clé et de valeur.

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schéma/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schéma/p"
    xsi:schemaLocation="http://www.springframework.org/schéma/beans 
http://www.springframework.org/schéma/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.w3codebox.Question">
<constructeur-arg value="11></constructeur-arg>
<constructeur-arg value="Qu'est-ce que Java ?"></constructeur-arg>
<constructeur-arg>
<map>
<entrée key="Java est un langage de programmation" value="Ajay Kumar"></entrée>
<entrée key="Java est une plateforme" value="John Smith"></entrée>
<entrée key="Java est une île" value="Raj Kumar"></entrée>
</map>
</constructeur-arg>
</bean>
</beans>

Test.java

Cette classe récupère le Bean à partir du fichier applicationContext.xml et appelle la méthode 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();
}
}