•Spring IOC 容器可以自動裝配 Bean. 需要做的僅僅是在 <bean> 的 autowire 屬性裡指定自動裝配的模式
•byType(根據類型自動裝配): 若 IOC 容器中有多個與目标 Bean 類型一緻的 Bean. 在這種情況下, Spring 将無法判定哪個 Bean 最合适該屬性, 是以不能執行自動裝配.
•byName(根據名稱自動裝配): 必須将目标 Bean 的名稱和屬性名設定的完全相同,若有比對的則進行自動裝配;若沒有比對的則不進行裝配.
•constructor(通過構造器自動裝配): 當 Bean 中存在多個構造器時, 此種自動裝配方式将會很複雜. 不推薦使用
自動裝配的缺點:
•在 Bean 配置檔案裡設定 autowire 屬性進行自動裝配将會裝配 Bean 的所有屬性. 然而, 若隻希望裝配個别屬性時, autowire 屬性就不夠靈活了.
•autowire 屬性要麼根據類型自動裝配, 要麼根據名稱自動裝配, 不能兩者兼而有之.
•一般情況下,在實際的項目中很少使用自動裝配功能,因為和自動裝配功能所帶來的好處比起來,明确清晰的配置文檔更有說服力一些
例如
application.xml
<bean id="address" class="com.hello.Address" p:city="淄博" p:road="柳泉路"/>
<bean id="userInfo2" class="com.hello.UserInfo" p:id="200" p:name="Hern" p:pass="456789" autowire="byName"/>
package com.hello;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class Address {
private String city;
private String road;
public Address() {
super();
}
public Address(String city, String road) {
this.city = city;
this.road = road;
}
}
package com.hello;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class UserInfo {
private int id;
private String name;
private String pass;
private Address address;
public UserInfo() {
super();
}
public UserInfo(int id, String name, String pass, Address address) {
this.id = id;
this.name = name;
this.pass = pass;
this.address = address;
}
}
package test;
import com.hello.UserInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainTest2 {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-application2.xml");
UserInfo userInfo = (UserInfo) applicationContext.getBean("userInfo2");
System.out.println(userInfo);
}
}