本篇文章介绍基于XML注入类似于List/Map/Set等集合类型或自定义Object类型的注入方式<br />[https://gitee.com/gao_xi/spring-demo1/tree/type-di-demo/](https://gitee.com/gao_xi/spring-demo1/tree/type-di-demo/)
1.各种类型的注入方式
<?xml version="1.0" encoding="UTF-8"?><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.xsd"><bean id="book" class="com.gao.Book"><property name="name" value="Java核心技术卷I"/><!--数组--><property name="array"><array><value>Java</value><value>编程四大名著</value></array></property><!--列表--><property name="list"><list><value>1</value><value>2</value></list></property><!--map--><property name="map"><map><entry key="11" value="12"></entry><entry key="12" value="12"></entry></map></property><!--set--><property name="set"><set><value>11</value><value>12</value></set></property><!--AnyType--><property name="author" ref="author"></property></bean><bean id="author" class="com.gao.Author"><property name="name" value="gaoxi"></property></bean></beans>
2.内部bean形式注入其他Bean
<bean id="book" class="com.gao.Book"><!--AnyType--><property name="author"><bean id="author" class="com.gao.Author"><property name="name" value="gaoxi"></property></bean></property></bean>
3.级联赋值
<bean id="book" class="com.gao.Book"><!--AnyType--><property name="author" ref="author"></property><property name="author.name" value="James"/></bean><bean id="author" class="com.gao.Author"><property name="name" value="gaoxi"></property></bean>
这种赋值方式的Book类需要提供对Author类的Getter方法
package com.gao;import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.Set;/*** @author GaoXi* @date 2021/8/13 19:31*/public class Book {// ........private Author author;public void setAuthor(Author author) {this.author = author;}public Author getAuthor() {return author;}// ........}
4.集合里面是自定义类类型
<bean id="book" class="com.gao.Book"><property name="authorList"><list><ref bean="author1"></ref><ref bean="author2"></ref></list></property></bean><bean id="author1" class="com.gao.Author"><property name="name" value="gaoxi"></property></bean><bean id="author2" class="com.gao.Author"><property name="name" value="高溪"/></bean>
