We can fill value or a list of values to a Java bean defined in Spring xml configuration file.
The following sections shows how to fill data to java.util.Properties.
In order to show how to use xml configuration file to fill collection properties, we defined a Customer object with four collection properties.
package com.java2s.common; import java.util.Properties; public class Customer { private Properties pros = new Properties(); public Properties getPros() { return pros; } public void setPros(Properties pros) { this.pros = pros; } public String toString(){ return pros.toString(); } }
Person Java Bean
package com.java2s.common; public class Person { private String name; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } }
java.util.Properties is a key-value pair structrue and we can use the following syntax to fill data for it.
... <property name="pros"> <props> <prop key="admin">user a</prop> <prop key="support">user b</prop> </props> </property> ...
Full Spring's bean configuration file.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="CustomerBean" class="com.java2s.common.Customer"> <!-- java.util.Properties --> <property name="pros"> <props> <prop key="admin">user a</prop> <prop key="support">user b</prop> </props> </property> </bean> <bean id="PersonBean" class="com.java2s.common.Person"> <property name="name" value="java2s1" /> <property name="address" value="address 1" /> <property name="age" value="28" /> </bean> </beans>
Here is the code to load and run the configuration.
package com.java2s.common; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); Customer cust = (Customer)context.getBean("CustomerBean"); System.out.println(cust); } }
Output
Customer [ pros={admin=user a, support=user b},