注意本文與一般spring 標注@Autowire 無關
如下例子定義了3個類 Dperson Dcar & Daddress
其中Dperson 要引用另外兩個類
Dperson
package com.home.autowire;
public class Dperson {
private String name;
private Dcar car;
private Daddress address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dcar getCar() {
return car;
}
public void setCar(Dcar car) {
this.car = car;
}
public Daddress getAddress() {
return address;
}
public void setAddress(Daddress address) {
this.address = address;
}
@Override
public String toString() {
return "Dperson [name=" + name + ", car=" + car + ", address="
+ address + "]";
}
}
Dcar
package com.home.autowire;
public class Dcar {
private String brand;
private int price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Dcar [brand=" + brand + ", price=" + price + "]";
}
}
Daddress
package com.home.autowire;
public class Daddress {
private String city;
private String street;
private int number;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Override
public String toString() {
return "Daddress [city=" + city + ", street=" + street + ", number="
+ number + "]";
}
}
注意下面引用了p Namespace
<bean id="car" class="com.home.autowire.Dcar" p:brand="Audi" p:price="10000"/>
<bean id="address" class="com.home.autowire.Daddress" p:city="Canton" p:street="teenho" p:number="103"/>
<!-- normal assemble -->
<bean id="person1" class="com.home.autowire.Dperson" p:name="Bill" p:car-ref="car" p:address-ref="address"/>
上面這個方法是最常用的, 也是最清晰的, 一般項目也推薦上面的方法。
在這個例子種, 所謂autowire 自動裝配就是指 不用在Dperson類的bean中手動指定每個屬性的值, spring會根據ByName或者ByType去找
ByName:
<bean id="car" class="com.home.autowire.Dcar" p:brand="Audi" p:price="10000"/>
<bean id="address" class="com.home.autowire.Daddress" p:city="Canton" p:street="teenho" p:number="103"/>
<!-- auto wire-->
<bean id="person2" class="com.home.autowire.Dperson" p:name="Lily" autowire="byName"/>
上面的例子例子, bean person2 會在spring xml種查找有沒有 跟屬性名一樣名字的bean, 有就裝配, 沒有則賦值null
ByType:
<bean id="car1" class="com.home.autowire.Dcar" p:brand="Audi" p:price="10000"/>
<bean id="address1" class="com.home.autowire.Daddress" p:city="Canton" p:street="teenho" p:number="103"/>
<!-- auto wire byType-->
<bean id="person3" class="com.home.autowire.Dperson" p:name="Jessie" autowire="byType"/>
萬一找不到跟屬性名一樣的bean, 也可以通過byTime來自動裝配的
autowire會令到spring 配置文件更加簡介, 但���可讀性下降了, 一般情況下其實不建議使用, 但是某些特殊情況, 例如spring 嵌入其他framework(strurt2 hibernate), autowire有時的確會使程序猿更加方便。