5.XML的自动装配

在xml 中可以使用autowire 属性配置自动装配方式:

  • byName: 根据bean的名字和当前bean的setter 风格的属性名进行自动装配,若匹配的,
    则自动装配;反之

  • byType: 根据bean的类型和当前bean 的属性的类型 进行自动装配.如IOC容器中有1个以上的类型匹配的bean,则抛出异常

    Address.java
package com.atguigu.spring.beans.autowire;

public class Address {
    private String city;
    private String street;
    
    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;
    }
    @Override
    public String toString() {
        return "Address [city=" + city + ", street=" + street + "]";
    }

}
Car.java
package com.atguigu.spring.beans.autowire;

public class Car {
    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;
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }
    
    

}
Person.java
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 + "]";
    }
    
    
}
Main.c
public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml");
       Person person = (Person) ctx.getBean("person");
       System.out.println(person);
    }

}
beans-autowire.xml

     
    
      
      
      

     

     

xml自动装配的缺点:

  • bean的所有属性都被自动装配,无法选择性自动装配,不灵活.
  • autowire的属性的两种方式不同时使用,只能选其一进行自动装配.

你可能感兴趣的:(5.XML的自动装配)