IOC(十一) - xml管理之自动装配
自动装配: 根据指定装配规则(属性名称或属性类型), Spring自动将匹配的属性值进行注入
实例:
byName
创建Department类:
public class Department { @Override public String toString() { return "Department{}"; } }
创建Employee类:
public class Employee { private Department dept; public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return "Employee{" + "dept=" + dept + '}'; } }
xml配置:(设置autowire="byName"后bean会自动根据属性名去注入相同id的对象)
<?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="dept" class="com.ryan.spring5.autowire.Department"></bean> <bean id="emp" class="com.ryan.spring5.autowire.Employee" autowire="byName"></bean> </beans>
测试:
Employee{dept=Department{}}
byType
修改xml文件设置:
autowire="byType"
结果相同, 但设置autowire="byType"时, xml中该类型的bean只能有一个, 否则会报错: