Bean 定義
bean 是一個被實例化,組裝,並通過 Spring IoC 容器所管理的對象。
bean 定義包含稱爲配置元數據的信息,下述容器也需要知道配置元數據:Bean由配置的元素數據創建。
屬性 | 描述 |
---|---|
class | 這個屬性是強制性的,並且指定用來創建 bean 的 bean 類。 |
name | 這個屬性指定唯一的 bean 標識符。在基於 XML 的配置元數據中,你可以使用 ID 和/或 name 屬性來指定 bean 標識符。 |
scope | 這個屬性指定由特定的 bean 定義創建的對象的作用域,它將會在 bean 作用域的章節中進行討論。 |
constructor-arg | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
properties | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
autowiring mode | 它是用來注入依賴關係的,並會在接下來的章節中進行討論。 |
lazy-initialization mode | 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啓動時去創建一個 bean 實例。 |
initialization 方法 | 在 bean 的所有必需的屬性被容器設置之後,調用回調方法。它將會在 bean 的生命週期章節中進行討論。 |
destruction 方法 | 當包含該 bean 的容器被銷燬時,使用回調方法。它將會在 bean 的生命週期章節中進行討論。 |
Spring 配置元數據
Spring IoC 容器完全由實際編寫的配置元數據的格式解耦。有下面三個重要的方法把配置元數據提供給 Spring 容器:
-
基於 XML 的配置文件
-
基於註解的配置
- 基於 Java 的配置
<?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-3.0.xsd"> <!-- A simple bean definition --> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- 延遲初始化的 bean 容器在它第一次被請求時,而不是在啓動時去創建一個 bean 實例--> <bean id="..." class="..." lazy-init="true"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- 在 bean 的所有必需的屬性被容器設置之後,調用回調方法--> <bean id="..." class="..." init-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- 當包含該 bean 的容器被銷燬時,使用回調方法。 --> <bean id="..." class="..." destroy-method="..."> <!-- collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions go here --> </beans>
Bean的生命週期
-
儘管還有一些在 Bean 實例化和銷燬之間發生的活動,,它們在 bean 的初始化和銷燬的時候是必需的。
爲了定義安裝和拆卸一個 bean,我們只要聲明帶有 init-method 和/或 destroy-method 參數的 。init-method 屬性指定一個方法,在實例化 bean 時,立即調用該方法。同樣,destroy-method 指定一個方法,只有從容器中移除 bean 之後,才能調用該方法。
Bean的生命週期可以表達爲:Bean的定義——Bean的初始化——Bean的使用——Bean的銷燬