1. 本篇文章介绍基于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.各种类型的注入方式

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="book" class="com.gao.Book">
  6. <property name="name" value="Java核心技术卷I"/>
  7. <!--数组-->
  8. <property name="array">
  9. <array>
  10. <value>Java</value>
  11. <value>编程四大名著</value>
  12. </array>
  13. </property>
  14. <!--列表-->
  15. <property name="list">
  16. <list>
  17. <value>1</value>
  18. <value>2</value>
  19. </list>
  20. </property>
  21. <!--map-->
  22. <property name="map">
  23. <map>
  24. <entry key="11" value="12"></entry>
  25. <entry key="12" value="12"></entry>
  26. </map>
  27. </property>
  28. <!--set-->
  29. <property name="set">
  30. <set>
  31. <value>11</value>
  32. <value>12</value>
  33. </set>
  34. </property>
  35. <!--AnyType-->
  36. <property name="author" ref="author"></property>
  37. </bean>
  38. <bean id="author" class="com.gao.Author">
  39. <property name="name" value="gaoxi"></property>
  40. </bean>
  41. </beans>

2.内部bean形式注入其他Bean

  1. <bean id="book" class="com.gao.Book">
  2. <!--AnyType-->
  3. <property name="author">
  4. <bean id="author" class="com.gao.Author">
  5. <property name="name" value="gaoxi"></property>
  6. </bean>
  7. </property>
  8. </bean>

3.级联赋值

  1. <bean id="book" class="com.gao.Book">
  2. <!--AnyType-->
  3. <property name="author" ref="author"></property>
  4. <property name="author.name" value="James"/>
  5. </bean>
  6. <bean id="author" class="com.gao.Author">
  7. <property name="name" value="gaoxi"></property>
  8. </bean>

这种赋值方式的Book类需要提供对Author类的Getter方法

  1. package com.gao;
  2. import java.util.Arrays;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.Set;
  6. /**
  7. * @author GaoXi
  8. * @date 2021/8/13 19:31
  9. */
  10. public class Book {
  11. // ........
  12. private Author author;
  13. public void setAuthor(Author author) {
  14. this.author = author;
  15. }
  16. public Author getAuthor() {
  17. return author;
  18. }
  19. // ........
  20. }

4.集合里面是自定义类类型

  1. <bean id="book" class="com.gao.Book">
  2. <property name="authorList">
  3. <list>
  4. <ref bean="author1"></ref>
  5. <ref bean="author2"></ref>
  6. </list>
  7. </property>
  8. </bean>
  9. <bean id="author1" class="com.gao.Author">
  10. <property name="name" value="gaoxi"></property>
  11. </bean>
  12. <bean id="author2" class="com.gao.Author">
  13. <property name="name" value="高溪"/>
  14. </bean>