1. 程式人生 > >Spring框架---Bean的自動裝配

Spring框架---Bean的自動裝配

SpringIOC容器可以自動裝配Bean,需要做的僅僅是在<bean>的autowrite屬性裡指定自動裝配模式。

byType(根據型別自動裝配):若在IOC容器中有多個目標Bean型別一致的Bean,在這種情況下,Spring將無法判斷哪個Bean最合適該屬性,所以不能執行自動裝配;
byName:(根據名稱自動裝配):必須將目標Bean的名稱和屬性名設定的完全相同。

constructor(通過構造器自動裝配):當Bean中存在多個構造器時,此種自動裝配方式將會很複雜 不推薦使用!

XML配置裡的Bean自動裝配的缺點:
在Bean配置檔案裡設定autowire屬性進行自動裝配將會裝配在Bean的所有屬性,然而,若只希望裝配個別屬性時,autowire屬性就不夠靈活了
autowire屬性要麼根據型別進行自動裝配,要麼根據名字自動裝配 二者不可以兼而有之
一般情況下,在實際的專案中很少使用自動裝配因為和自動裝配功能所帶來的好處比起來,明確清晰地配置文件更有說服力

下面是程式碼的測試  開始測試之前需要三個類 和一個測試類

package com.imooc.spring.spring_day01;


public class Adress {
private String city;
private String stree;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStree() {
return stree;
}
public void setStree(String stree) {
this.stree = stree;
}
@Override
public String toString() {
return "Adress [city=" + city + ", stree=" + stree + "]";
}

}

package com.imooc.spring.spring_day01;


public class CarAutowire {
private String brand;
private double price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

package com.imooc.spring.spring_day01;


public class PersonAutowire {
private String name;
private CarAutowire car;
private Adress adress;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CarAutowire getCar() {
return car;
}
public void setCar(CarAutowire car) {
this.car = car;
}
public Adress getAdress() {
return adress;
}
public void setAdress(Adress adress) {
this.adress = adress;
}
@Override
public String toString() {
return "PersonAutowire [name=" + name + ", car=" + car + ", adress=" + adress + "]";
}

}

//測試類

@Test
public void test01() {
ApplicationContext context = new 
ClassPathXmlApplicationContext("applicationAutowire.xml");
PersonAutowire person = (PersonAutowire) context.getBean("person");
System.out.println(person);
}

//配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="adress" class="com.imooc.spring.spring_day01.Adress"
p:city="BeiJing" p:stree="海淀區"></bean>

<bean id="car" class="com.imooc.spring.spring_day01.CarAutowire"
p:brand="BaoMa"  p:price="30000"></bean>
<!-- 可以使用autowire 屬性指定自動裝配的方式 
byName 根據bean的和當前bean的setter風格的屬性名進行 裝配,若有匹配的,則自動裝配,若沒有匹配,則不匹配
byType 根據bean的型別和當前bean的屬性的型別進行自動裝配 若IOC容器中有一個以上的型別匹配,則會丟擲異常-->
<!-- <bean id="person" class="com.imooc.spring.spring_day01.PersonAutowire"
p:name="Tom" autowire="byName"></bean> -->
<bean id="person" class="com.imooc.spring.spring_day01.PersonAutowire"
p:name="Tom" autowire="byType"></bean>
</beans>