Spring Map、Set、List、Array、Properties属性的注入 - TFdream/blog GitHub Wiki

1. bean

Department

import java.util.List;  
import java.util.Map;  
import java.util.Properties;  
import java.util.Set;  
  
public class Department {  
  
    private String name;  
    private String [] empName;//数组  
    private List<Employee> empList;//list集合  
    private Set<Employee> empSet;//set集合  
    private Map<String, Employee> empMap;//map集合  
    private Properties props;//Properties的使用  

    //省略setter/getter
    ......
}

Employee

public class Employee {  
    private Long id;  
    private String name;  
    
    //省略setter/getter
    ......
}

2. spring-core.xml

<?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:tx="http://www.springframework.org/schema/tx"
	   xmlns:util="http://www.springframework.org/schema/util"
	   xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
       		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<bean id="dept" class="com.mindflow.demo.Department">  
		<property name="name" value="RD"/>  
		  
		<!-- 给数组注入值 -->  
		<property name="empName">  
			<list>  
				<value>Ricky</value>  
				<value>Jack</value>  
				<value>Mike</value>  
			</list>  
		</property>  
		  
		<!-- 给list注入值 list 中可以有相当的对象 -->  
		<property name="empList">  
			<list>  
				<ref bean="emp1" />  
				<ref bean="emp2"/>  
				<ref bean="emp3"/>
			</list>  
		</property>
		  
		<!-- 给set注入值 set不能有相同的对象 -->  
		<property name="empSet">  
			<set>  
				<ref bean="emp1" />  
				<ref bean="emp2"/>  
				<ref bean="emp3"/> 
			</set>  
		</property>  
		  
		<!-- 给map注入值 map只有key不一样,就可以装配value -->  
		<property name="empMap">  
			<map>  
				<entry key="1" value-ref="emp1" />   
				<entry key="2" value-ref="emp2"/>  
				<entry key="3" value-ref="emp3"/>  
			</map>  
		</property>  
		
		<!-- 给属性集合配置 -->  
		<property name="props">  
			<props>  
				<prop key="key1">hello</prop>  
				<prop key="key2">world</prop>  
			</props>  
		</property>  
	</bean>  
  
	<bean id="emp1" class="com.mindflow.demo.Employee">  
		<property name="id" value="1"/>  
		<property name="name" value="ricky"/>  
	</bean>
	
	<bean id="emp2" class="com.mindflow.demo.Employee">  
		<property name="id" value="2"/>  
		<property name="name" value="jack"/>  
	</bean>  
	<bean id="emp3" class="com.mindflow.demo.Employee">  
		<property name="id" value="3"/>  
		<property name="name" value="mike"/>  
	</bean>
</beans>  
⚠️ **GitHub.com Fallback** ⚠️