上篇介紹了 Setter 注入,本文深入講解構造器注入、簡化配置的 P 命名空間、以及 List/Set/Map/數組等集合類型的注入方式。
public class Student {
private String name;
private Integer age;
private Car car;
public Student(String name, Integer age, Car car) { // 帶參構造
this.name = name;
this.age = age;
this.car = car;
}
public Student() {} // 無參構造(可選)
// getter/setter/toString 省略
}
public class Car {
private String color;
// getter/setter/toString 省略
}
<bean id="car" class="cn.wz.entity.Car">
<property name="color" value="白色"/>
</bean>
<bean id="stu" class="cn.wz.entity.Student">
<!-- index 從 0 開始對應構造器參數位置 -->
<constructor-arg index="0" value="王哲"/>
<constructor-arg index="1" value="18"/>
<constructor-arg index="2" ref="car"/>
</bean>
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = ctx.getBean("stu", Student.class);
System.out.println(student);
// 輸出: Student [name=王哲, age=18, car=Car [color=白色]]
引入命名空間:xmlns:p="https://www.springframework.org/schema/p"
<bean id="car" class="cn.wz.entity.Car" p:color="白色"/>
<bean id="stu" class="cn.wz.entity.Student"
p:name="王哲" p:age="18" p:car-ref="car" />
規則:p:屬性名 對應 Setter,p:屬性名-ref 對應引用類型注入。效果等同於 <property> 但更簡潔。
<bean id="list" class="cn.wz.entity.Student">
<property name="list">
<list>
<value>王哲</value>
<value>張一銘</value>
</list>
</property>
</bean>
<bean id="set" class="cn.wz.entity.Student">
<property name="set">
<set>
<value>王哲</value>
<value>張一銘</value>
</set>
</property>
</bean>
<bean id="map" class="cn.wz.entity.Student">
<property name="map">
<map>
<entry key="wz"><value>王哲</value></entry>
<entry key="zym"><value>張一銘</value></entry>
</map>
</property>
</bean>
<bean id="array" class="cn.wz.entity.Student">
<property name="array">
<list> <!-- 數組也用 list 標簽 -->
<value>王哲</value>
<value>張一銘</value>
</list>
</property>
</bean>
| 注入方式 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Setter 注入 | 可讀性強、可選依賴、支持重新配置 | 對象創建後才注入、循環依賴風險 | 大多數場景、可選依賴 |
| 構造器注入 | 不可變性、強制依賴、線程安全 | 參數多時配置繁瑣、不支持循環依賴 | 必須依賴、不可變對象 |
| P 命名空間 | XML 簡潔、可讀性高 | IDE 提示較弱、複雜類型受限 | 簡單屬性、大量 Bean 配置 |
實際項目中常混合使用:核心依賴用構造器注入保證完整性,可選配置用 Setter/P 命名空間,集合類型按業務選擇 List/Set/Map。