使用自动装配可以让Spring对IOC容器中的bean的引用进行自动装配。
其中,自动装配分为两种,一是通过名字装配,二是通过类型进行装配
一、通过名字装配
使用byName来进行自动装配,这时候如果IOC容器中存在一个bean的id与需要装配的类的setter方法相对应的话,Spring就会对其进行自动装配,如果找不到与setter对应的bean的话,则会置为null
还是之前用的Person类和Address类:
package beans;
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 + "]";
}
}
package beans;
public class Person {
private String name;
private Address address;
@Override
public String toString() {
return "Person [name=" + name + ", address=" + address + "]";
}
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;
}
}
然后是Spring的配置文件:
<?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="address" class="beans.Address">
<property name="city" value="GuangZhou1"></property>
<property name="street" value="Shangxiajiu"></property>
</bean>
<bean id="person" class="beans.Person"
p:name="Tom" autowire="byName"></bean>
</beans>
这里我们可以很明显的看到在Address的实例化对象中,id=“address”,在Person的类中Setter方法为setAddress(),这样称为是对应的,因此使用autowire=“byName”方法时可以自动使用第一个bean为person赋值。当我们把Address的id改为address1时,自动装配就不会将第一个bean为person赋值,因为它们不对应了,此时,需要把Person的setter方法改为setAddress1()即可使自动装配再次生效
最后写个main方法测试一下:
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person)ctx.getBean("person");
System.out.println(person);
}
}
二、通过类型进行装配
使用byType来进行自动装配,这时候如果IOC容器中存在一个bean的类与需要装配的类的setter方法参数类型相对应的话,Spring就会对其进行自动装配,如果找不到与setter对应的bean的话,则会置为null,如果存在多个对应的bean的话,会报错,因为Spring不知道应该装配哪个
Person类和Address类都不变,只需要在上面的基础上将autowire=“byName”改为“byType”即可,此处便不再累赘