自动装配
什么是自动装配
根据指定的装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
前面使用的装配方式都是手动装配
package com.test3; public class Emp { private String name; private Dpt dpt; public void setName(String name) { this.name = name; } public void setDpt(Dpt dpt) { this.dpt = dpt; } @Override public String toString() { return "Emp{" + "name='" + name + '\'' + ", dpt=" + dpt + '}'; } public void test(){ System.out.println(dpt); } }
package com.test3; public class Dpt { private String name; public void setName(String name) { this.name = name; } @Override public String toString() { return "Dpt{" + "name='" + name + '\'' + '}'; } }
<?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="emp" class="com.test3.Emp"> <property name="dpt" ref="dpt"/> </bean> <bean id="dpt" class="com.test3.Dpt"/> </beans>
package com.test3; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; public class EmpTest { @Test public void test1() { ApplicationContext context = new ClassPathXmlApplicationContext("spring9.xml"); Emp emp = context.getBean("emp", Emp.class); System.out.println("emp = " + emp); } }
演示自动装配
<?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标签有一个属性autowire,配置自动装配 autowire属性有两个常用的值: byName 根据属性名称注入 注入的bean的id值和类属性名称一致 byType 根据属性类型注入 注入的bean的class不能相同 --> <!--<bean id="emp" class="com.test3.Emp" autowire="byName"> <property name="dpt" ref="dpt"/> </bean>--> <bean id="emp" class="com.test3.Emp" autowire="byType"> <!--<property name="dpt" ref="dpt"/>--> </bean> <bean id="dpt" class="com.test3.Dpt"/> </beans>