Spring-IoC-Bean管理(基於xml自動裝配)
阿新 • • 發佈:2020-08-16
基於xml自動裝配(實際開發中很少用)
1.什麼是自動裝配?
(1)根據指定裝配規則(屬性名稱或者屬性型別),spring自動裝配的屬性值進行注入
2.示例
(1)建立類
package com.company.spring5.test1; /** * @author orz * @create 2020-08-15 22:01 */ public class Dept { public String dname; public void setDname(String dname) { this.dname = dname; } @Overridepublic String toString() { return "Dept{" + "dname='" + dname + '\'' + '}'; } }
package com.company.spring5.test1; /** * @author orz * @create 2020-08-15 22:01 */ public class Emp { private Dept dept; public void setDept(Dept dept) {this.dept = dept; } @Override public String toString() { return "Emp{" + "dept=" + dept + '}'; } }
(2)配置檔案
<?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"> <!-- 實現自動裝配 1.bean標籤屬性autowire,配置自動裝配 autowire屬性常用兩個值: byName:根據名稱注入,注入值bean的id和類屬性名稱一致 byType:根據屬性型別注入,相同型別的bean不能定義多個 --> <bean id="emp3" class="com.company.spring5.test1.Emp" autowire="byType"> </bean> <bean id="dept3" class="com.company.spring5.test1.Dept"></bean> </beans>
(3)測試
package com.company.spring5.test1; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author orz * @create 2020-08-15 22:06 */ public class Test1 { @Test public void test3() { ApplicationContext context=new ClassPathXmlApplicationContext("bean8.xml"); Emp emp = context.getBean("emp3", Emp.class); System.out.println(emp); } }
(4)結果
Emp{dept=Dept{dname='null'}}