1.新建实体类
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 + "]"; } }
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 + "]"; } }
public class Person { private String name; private Car car; private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "Person [name=" + name + ", car=" + car + ", address=" + address + "]"; } }
2.XML文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.auguigu.spring.beans.autowire.Address"> <property name="city" value="BeiJing"></property> <property name="street" value="HuiLongGuan"></property> </bean> <bean id="car" class="com.auguigu.spring.beans.autowire.Car"> <property name="brand" value="Audi"></property> <property name="price" value="30000"></property> </bean> <bean id="person" class="com.auguigu.spring.beans.autowire.Person" autowire="byName"> <property name="name" value="Tom"></property> </bean> </beans>
3.测试类
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-autowire.xml"); Person p = (Person) ctx.getBean("person"); System.out.println(p); } }
byName根据bean的id和当前setter属性名自动装配
byType 根据bean的类型和当前bean的属性的类型自动装配,但是,若IOC容器有一个以上的类型匹配的bean,则抛出异常