English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questo esempio, utilizziamo
map
è una risposta con nome utente pubblicato. In questo esempio, utilizzeremo entrambi le chiavi e i valori come stringhe.
Come nell'esempio precedente, è un esempio di forum, dove
Una domanda può avere più risposte
。
Question.java
Questa classe contiene tre attributi, due costruttori e il metodo displayInfo() per visualizzare le informazioni.
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 domanda:" + id); System.out.println("nome domanda:" + name); System.out.println("Risposte...."); 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("Risposta:\""+entry.getKey()+" Pubblicato Da:\""+entry.getValue()+"\"); } } }
applicationContext.xml
map
del
entry Proprietà utilizzate per definire informazioni chiave e valore.
<?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="Cos'è Java?"></constructor-arg> <constructor-arg> <map> <entry key="Java è un linguaggio di programmazione" value="Ajay Kumar"></entry> <entry key="Java è una piattaforma" value="John Smith"></entry> <entry key="Java è un'isola" value="Raj Kumar"></entry> </map> </constructor-arg> </bean> </beans>
Test.java
Questa classe recupera un Bean dal file applicationContext.xml e chiama il metodo 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(); } }