byName:通过名称进行自动匹配;
byType:根据类型进行自动匹配;
constructor:和 byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;
建议:自动装配机制慎用,它屏蔽了装配细节,容易产生潜在的错
byName实例分析:
(还把dog这个bean装配到people中)
beans.xml (byName方式自动装配bean)
<?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"
default-autowire="byName">
<bean id="dog" class="com.java1234.entity.Dog">
<property name="name" value="Jack"></property>
</bean>
<bean id="dog1" class="com.java1234.entity.Dog">
<property name="name" value="Tom"></property>
</bean>
//加上 default-autowire="byName"属性,people中自动装配id="dog",控制台输出的dog名字是jack
<bean id="people1" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
</bean>
beans.xml (byType方式自动装配bean)只要有dog类型的对象就可以自动装配该名为dog的beandaopeople中
<?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"
default-autowire="byType">
<bean id="dog2" class="com.java1234.entity.Dog">
<property name="name" value="Tom"></property>
</bean>
//加上 default-autowire="byType"属性,people中自动装配id="dog2",控制台输出的dog名字是Tom
<bean id="people1" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
</bean>
constructor:和 byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;
<?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"
default-autowire="constructor">
//输出jack
<bean id="dog2" class="com.java1234.entity.Dog">
<property name="name" value="Jack"></property>
</bean>
<bean id="people1" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
</bean>
</beans>
people中要加上下面这个构造方法
public People(Dog dog) {
super();
System.out.println("constructor");
this.dog = dog;
}