【Spring】(3.6)自動裝配

一、自動裝配

該篇文章講自動裝配。使用的是xml配置文件方式。

項目結構:
在這裏插入圖片描述

創建實體類

public class Cat {
}
public class Dog {
}
public class People {
    private Cat cat;
    private Dog dog;

    @Override
    public String toString() {
        return "People{" +
                "cat=" + cat +
                ", dog=" + dog +
                '}';
    }

    public People() {
    }

    public People(Cat cat, Dog dog) {
        this.cat = cat;
        this.dog = dog;
    }

    public Cat getCat() {
        return cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

編寫配置文件。

注意:如果使用autowire=“constructor”,則自動裝配的類中,需要有所有屬性的帶參構造器。

<?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="cat" class="com.shengjava.pojo.Cat"/>
    <bean id="dog" class="com.shengjava.pojo.Dog"/>

    <!-- 沒有使用自動裝配之前,我們需要自己手動注入對象到People對象的屬性中(使用People類的無參構造器) -->
    <bean id="peopleBefore" class="com.shengjava.pojo.People">
        <property name="cat" ref="cat"></property>
        <property name="dog" ref="dog"></property>
    </bean>

    <!-- 使用自動裝配之後則不需要。autowire屬性:byType(依靠類型)、byName(依靠變量名和bean的id)、constructor(類似於byType,要有帶參構造器)、no(默認爲no,不使用自動裝配)-->
    <bean id="peopleAfter" class="com.shengjava.pojo.People" autowire="byType"></bean>

</beans>

測試類

public class PeopleTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        // 沒有使用自動裝配之前
        People peopleBefore = context.getBean("peopleBefore", People.class);
        System.out.println(peopleBefore);
        // 使用自動裝配
        People peopleAfter = context.getBean("peopleAfter", People.class);
        System.out.println(peopleAfter);
    }
}

輸出

People{cat=com.shengjava.pojo.Cat@49d904ec, dog=com.shengjava.pojo.Dog@48e4374}
People{cat=com.shengjava.pojo.Cat@49d904ec, dog=com.shengjava.pojo.Dog@48e4374}

以上就是自動裝配,現在是使用的xml配置方式,但是這種方式比較複雜,後面會有更簡單的自動裝配方式(使用註解)。

參考:1.4.5. Autowiring Collaborators


相關

我的該分類的其他相關文章,請點擊:【Spring】文章目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章