Spring4学习笔记(五):Bean的自动装配

Spring IOC 容器可以自动装配 Bean. 需要做的仅仅是在 的 autowire 属性里指定自动装配的模式
1、byType(根据类型自动装配): 若 IOC 容器中有多个与目标 Bean 类型一致的 Bean. 在这种情况下, Spring 将无法判定哪个 Bean 最合适该属性, 所以不能执行自动装配.
2、byName(根据名称自动装配): 必须将目标 Bean 的名称和属性名设置的完全相同.
3、constructor(通过构造器自动装配): 当 Bean 中存在多个构造器时, 此种自动装配方式将会很复杂. 不推荐使用


<bean id="car" class="com.spring.autowire.Car" p:carBrand="Aodi" p:carPrice="300000">
    bean>
    <bean id="address" class="com.spring.autowire.Address" p:addressNum="111" p:addressName="文化街">bean>
    
    
    
    <bean class="com.spring.autowire.Person" p:name="张三" autowire="byName">bean>
//Person.java
package com.spring.autowire;

public class Person {
    private String name;
    private Address address;
    private Car car;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", address=" + address + ", car=" + car
                + "]";
    }

}
package com.spring.autowire;

public class Address {
    private String addressNum;
    private String addressName;
    public String getAddressNum() {
        return addressNum;
    }
    public void setAddressNum(String addressNum) {
        this.addressNum = addressNum;
    }
    public String getAddressName() {
        return addressName;
    }
    public void setAddressName(String addressName) {
        this.addressName = addressName;
    }
    @Override
    public String toString() {
        return "Address [addressNum=" + addressNum + ", addressName="
                + addressName + "]";
    }

}
package com.spring.autowire;

public class Car {
    private String carBrand;
    private String carPrice;
    public String getCarBrand() {
        return carBrand;
    }
    public void setCarBrand(String carBrand) {
        this.carBrand = carBrand;
    }
    public String getCarPrice() {
        return carPrice;
    }
    public void setCarPrice(String carPrice) {
        this.carPrice = carPrice;
    }
    @Override
    public String toString() {
        return "Car [carBrand=" + carBrand + ", carPrice=" + carPrice + "]";
    }

}

优缺点:
在 Bean 配置文件里设置 autowire 属性进行自动装配将会装配 Bean 的所有属性. 然而, 若只希望装配个别属性时, autowire 属性就不够灵活了.
autowire 属性要么根据类型自动装配, 要么根据名称自动装配, 不能两者兼而有之.
一般情况下,在实际的项目中很少使用自动装配功能,因为和自动装配功能所带来的好处比起来,明确清晰的配置文档更有说服力一些

你可能感兴趣的:(javaweb框架,javaweb)