第三講: 3.2 spring 依賴注入
一,通過屬性注入 1. 在beans.xml中,定義id為 people2 ,class屬性不變的bean,並給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"
1. 在beans.xml中,定義id為people4,class屬性不變的bean,並通過構造的順序給屬性賦值。 <bean id="people4" class="com.cruise.entity.People"> <constructor-arg index="0" value="4">constructor-arg> <constructor-arg index="1" value="王五">constructor-arg> <constructor-arg index="2" value="44">constructor-arg> bean>2. 在Test2中,新增程式碼獲取people4,執行-測試 People people4 = (People)CA.getBean("people4"); System.out.println(people4);
1. 在beans.xml中,定義id為people5,class屬性不變的bean,並通過構造的順序和構造的型別聯合給屬性賦值。 <bean id="people5" class="com.cruise.entity.People"> <constructor-arg index="0" type="int" value="5">constructor-arg> <constructor-arg index="1" type="String" value="趙六">constructor-arg> <constructor-arg index="2" type="int" value="55">constructor-arg> bean>2. 在Test2中,新增程式碼獲取people5,執行-測試 People people5 = (People)CA.getBean("people5"); System.out.println(people5);三,通過工廠方法注入 1. 新建一個包:com.cruise.factory ,新建類:PeopleFactory,寫返回值型別為People的createPeople()方法:new People(),設定屬性,返回例項,package com.cruise.factory;import com.cruise.entity.People;public class PeopleFactory { public People createPeople(){ People people = new People(); people.setId(6); people.setName("小七"); people.setAge(66); return people; } }2. 在beans.xml中,定義id為peopleFactory ,class為com.cruise.factory.PeopleFactory的bean; 再定義一個工廠bean,指令id為people6,指定工廠名為peopleFactory(保持一致),指定工廠裡的方法createPeople(保持一致) <bean id="peopleFactory" class="com.cruise.factory.PeopleFactory"></bean> <bean id="people6" factory-bean="peopleFactory" factory-method="createPeople"></bean>3. 在Test2類中新增程式碼,獲取people6,執行-測試,這是一個非靜態的工廠 People people6 = (People)CA.getBean("people6"); System.out.println(people6);
1. 新建類:PeopleFactory2,寫返回值型別為People的createPeople()靜態方法:new People(),設定屬性,返回例項,package com.cruise.factory;import com.cruise.entity.People;public class PeopleFactory2 { public static People createPeople(){ People people = new People(); people.setId(7); people.setName("老八"); people.setAge(77); return people; } }2. 在beans.xml中,定義id為peopleFactory ,class為com.cruise.factory.PeopleFactory的bean; 再定義一個工廠bean,指令id為people7,不需要指定工廠名為peopleFactory,直接指定工廠裡的方法createPeople(保持一致) <bean id="people7" class="com.cruise.factory.PeopleFactory2" factory-method="createPeople"></bean>3. 在Test2類中新增程式碼,獲取people7,執行-測試,這是一個靜態的工廠 People people7 = (People)CA.getBean("people7"); System.out.println(people7);