4. Spring 如何通過 XML 文件配置Bean,以及如何獲取Bean


在 Spring 容器內拼湊 bean 叫做裝配。裝配 bean 的時候,你是在告訴容器,需要哪些 bean ,以及容器如何使用依賴注入將它們配合在一起。

理論上,bean 裝配的信息可以從任何資源獲得,包括屬性文件,關系數據庫等,但 XML 文件是最常見的 Spring 應用系統配置源, Spring 中的幾種容器都支持使用 XML 裝配 bean,包括:

  --XMLBeanFactory

  --ClassPathXMLApplicationContext

  --FileSystemXMLApplicationContext

  --XMLWebApplicationContext

其中我們常用的有 ClassPathXMLApplicationContext,FileSystemXMLApplicationContext 兩種。

 

在 XML 文件中配置 bean 包括以下幾個方面:

  1. 添加 bean

  2. 配置 bean 屬性

    2.1 手動配置

      2.1.1 通過 setter 方法

      2.1.2 通過 constructor

    2.2 自動配置

 

下面,我們來添加 bean,並通過 setter 方法來對 bean 的屬性來進行配置:

  首先,先寫兩個 bean ,分別是 Person 和 Address , 其中 Person 是依賴於 Address 的。下面附上代碼:

package com.spring.xmlBean;

public class Person {
    private String name;
    private int age;
    private Address address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Person(String name, int age, Address address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public Person() {
        super();
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";
    }

}
Person 類
package com.spring.xmlBean;

public class Person {
    private String name;
    private int age;
    private Address address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Person(String name, int age, Address address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public Person() {
        super();
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";
    }

}
Address 類

  類寫完之后,我們在 classpath 下創建一個 Spring Bean Configuration File

創建完 XML 文件之后,我們開始在這個文件里配置 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">
    
    <!-- 添加 Address 和 Person -->
    <bean id="address" class="com.spring.xmlBean.Address"></bean>
    
    <bean id="person" class="com.spring.xmlBean.Person"></bean>
</beans>
Spring Bean Configuration File

在這里,我們通過 <bean></bean> 節點來添加 bean ,其中 class 屬性代表 bean 的全類名, id 屬性用來對 bean 進行標示,在調用 bean 的時候會使用這個 id 名,這個名字是唯一的,在配置文件中不能有重復,否則 Spring 會報錯

添加完 bean 之后,我們先來測試一下,看能不能獲取到這個 bean。我們先試着獲取一下 Person

package com.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.helloworld.HelloWorld;
import com.spring.xmlBean.Person;

public class TestMain {
    public static void main(String[] args) {
        
        // 創建 Spring 的 IOC 容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beanConfiguration-xml.xml");
        // 使用 getBean() 方法, 通過傳入剛才的 id 名,來獲取 bean, 但是這里返回的是一個 Object 對象, 所以要轉型
        Person person = (Person) ctx.getBean("person");
        // 打印 person
        System.out.println(person);
    }
}
TestMain

運行 main 方法,控制台輸出了以下信息

我們看到,我們成功的獲取到了 person,但是,person 中的屬性是空的,因為我們還沒有配置他們,只是單純的把它們添加到容器里面

那么現在,我們就來手動配置一下這兩個 bean

前面講過,手動配置 bean 有兩種方式,一種是通過 setter 方法,一種是通過 構造器(constructor)來配置。下面,我們都試一下:

1. 通過 setter 方法

  首先,需要注意的是,若要通過 setter 方法來配置 bean ,那么這個 bean 里面一定要有 setter 方法,否則 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 http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- 添加 Address 和 Person -->
    <bean id="address" class="com.spring.xmlBean.Address">
        <property name="city" value="日照"></property>
        <property name="province" value="山東"></property>
    </bean>
    
    <bean id="person" class="com.spring.xmlBean.Person">
        <property name="name" value="Little-Koala"></property>
        <property name="age" value="18"></property>
        <!-- 通過 ref 引用了 address 這個 bean -->
        <property name="address" ref="address"></property>
    </bean>
</beans>
Spring Bean Configuration File

運行剛才測試用的那個 main 方法,發現配置成功了

在配置的時候,我們使用了 <property name="屬性名"  value="值" ></property> 這個節點來對 bean 進行配置

其中,我們的 person 中有一個 Address 屬性,它通過 ref 這個屬性節點引用了 id 值為 address 的 bean

總結:通過 setter 方法來配置 bean ,我們使用 property 節點來進行配置,但前提是這個 bean 要有 setter 方法。其中,name 屬性表示 bean 的屬性名,bean 的屬性值可以通過 value 屬性來直接設置,也可以通過 ref 屬性來引用其他的 bean

 

2. 通過構造器來進行配置

  首先要注意的問題,在配置之前要有自己的構造器。我們通過 <constructor-arg></constructor-arg> 這個節點來進行配置,下面附上代碼:

<bean id="address" class="com.spring.xmlBean.Address">
        <constructor-arg name="city" value="日照"></constructor-arg>
        <constructor-arg name="province" value="山東"></constructor-arg>
        <!-- 
        <property name="city" value="日照"></property>
        <property name="province" value="山東"></property>
         -->
</bean>
Spring Bean Configuration File

上面的 Address 這個 bean 換成了用構造器來配置,運行的效果和上面是一樣的

其中,name 代碼構造器中屬性的名字,value 代表值

 

剛才上面說了怎樣配置 bean ,還沒有具體的講怎么樣從容器中獲取 bean

獲取bean分兩步:

  1. 創建 IOC 容器

  2. 從容器中獲取 bean

下面附上代碼:

package com.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.helloworld.HelloWorld;
import com.spring.xmlBean.Person;

public class TestMain {
    public static void main(String[] args) {
        
        // 創建 Spring 的 IOC 容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beanConfiguration-xml.xml");
        // 使用 getBean() 方法, 通過傳入剛才的 id 名,來獲取 bean, 但是這里返回的是一個 Object 對象, 所以要轉型
        Person person = (Person) ctx.getBean("person");
        // 打印 person
        System.out.println(person);
    }
}
怎樣獲取 Bean

這是剛才的那個測試類

其中 getBean( ) 方法可以通過傳入 id 值來獲取 IOC 容器中的 bean ,也可以通過傳入 Bean.class 來獲取對應類型的對象

 

以上內容都是基礎的內容,還有一部分沒有提到,剩下的那些內容在以后的學習中會慢慢接觸,多讀源碼,多看文檔,慢慢的就會了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM