自动装配
<bean>的autowire属性里指定自动装配--byType根据类型自动装配--byName根据名称自动装配所有的引用都要装配
byType或者byName不能兼有package autowire;public class Car { private String brand; private double price; public Car() { } public Car(String brand, double price) { this.brand = brand; this.price = 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 + '}'; }}
package autowire;public class Address { private String city; private String street; public Address() { } public Address(String city, String street) { this.city = city; this.street = 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 + '\'' + '}'; }}
package autowire;public class Person { String name; Address address; Car car; public Person() { } public Person(String name, Address address, Car car) { this.name = name; this.address = address; this.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 autowire;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("autowire//autowire.xml"); Person p1 = (Person)ctx.getBean("person1"); System.out.println(p1); Person p2 = (Person)ctx.getBean("person2"); System.out.println(p2); }}