English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
We can inject collection values through setter methods in the Spring framework. property Three elements can be used within an element. They can be:
List Set Map
Each collection can have values based on strings and non-string values. In this example, we take "forum" as an example, where A question can have multiple answersThere are a total of three pages:
Question.java applicationContext.xml Test.java
In this example, the list we use can contain duplicate elements, and you can use a set that contains only unique elements. However, you need to change the list set in applicationContext.xml and the list set in Question.java.
Question.java
This class contains three properties with setters and getters to retrieve information, as well as the displayInfo() method. Here, we use a list to contain multiple answers.
package com.w3codebox; import java.util.Iterator; import java.util.List; public class Question { private int id; private String name; private List<String> answers; //setters and getters public void displayInfo(){ System.out.println(id+" "+name); System.out.println("answers are:"); Iterator<String> itr=answers.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } }
applicationContext.xml
Here, builder is used-The list element defines a list for arg.
<?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="What is Java?"></property>/property> <property name="answers"> <list> <value>Java is a programming language</value>/value> <value>Java is a platform</value>/value> <value>Java is an Island</value>/value> </list> </property> </bean> </beans>
Test.java
This class retrieves a Bean from the applicationContext.xml file and calls the displayInfo method.
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(); } }