spring的學習日記-spring-的自動裝配bean1-xml的裝配方式
阿新 • • 發佈:2022-03-04
Spring的自動裝配,基於xml的方式,使用byName或者byType的方式
在bean中我們使用自動裝配,有2種方式:byName或者byType
byName的方式:使用該方式,我們的id屬性的值必需和實體類中set方法的後面的名字相同
byType的方式:使用該方式,我們註冊bean的時候,相同型別的bean只能註冊一個可以省略id屬性的值
pojo層:
package com.fu.pojo; public class People { private Dog dog; private Cat cat; public People(Dog dog, Cat cat) {this.dog = dog; this.cat = cat; System.out.println("我是有參構造建立的方式"); } public People() { System.out.println("我是無參構造建立的方式"); } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; System.out.println("set賦值方式"); } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; System.out.println("set賦值方式"); } @Override public String toString() { return "People{" + "dog=" + dog + ", cat=" + cat + '}'; } }
package com.fu.pojo; public class Dog { public void shout(){ System.out.println("我是狗"); } }
package com.fu.pojo; public class Cat { public void shout(){ System.out.println("我是貓"); } }
spring的xml:
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 註冊bean--> <bean id="dog" class="com.fu.pojo.Dog"/> <bean id="cat" class="com.fu.pojo.Cat"/> <!-- <bean id="people" class="com.fu.pojo.People" autowire="byName"/>--> <bean id="people" class="com.fu.pojo.People" autowire="byType"/> </beans>
測試類:
import com.fu.pojo.People; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /* Bean的自動裝配:byType方式,使用通過型別的方式進行匹配,在xml中我們只能註冊一個類同型別的bean,不能註冊多個 byName方式,通過id的屬性值進行匹配,該id的值必需和實體類中set方法後面的值相同 */ public class MyTest { public static void main(String[] args) { //獲取IOC容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //有了容器,我們就get到what People people = context.getBean("people", People.class); people.getCat().shout(); people.getDog().shout(); } }
測試結果: