被稱作 bean 的對象是構成應用程序的支柱也是由 Spring IoC 容器管理的。bean 是一個被實例化,組裝,并通過 Spring IoC 容器所管理的對象。這些 bean 是由用容器提供的配置元數據創(chuàng)建的,例如,已經在先前章節(jié)看到的,在 XML 的表單中的 定義。
bean 定義包含稱為配置元數據的信息,下述容器也需要知道配置元數據:
如何創(chuàng)建一個 bean
bean 的生命周期的詳細信息
上述所有的配置元數據轉換成一組構成每個 bean 定義的下列屬性。
屬性 | 描述 |
---|---|
class | 這個屬性是強制性的,并且指定用來創(chuàng)建 bean 的 bean 類。 |
name | 這個屬性指定唯一的 bean 標識符。在基于 XML 的配置元數據中,你可以使用 ID 和/或 name 屬性來指定 bean 標識符。 |
scope | 這個屬性指定由特定的 bean 定義創(chuàng)建的對象的作用域,它將會在 bean 作用域的章節(jié)中進行討論。 |
constructor-arg | 它是用來注入依賴關系的,并會在接下來的章節(jié)中進行討論。 |
properties | 它是用來注入依賴關系的,并會在接下來的章節(jié)中進行討論。 |
autowiring mode | 它是用來注入依賴關系的,并會在接下來的章節(jié)中進行討論。 |
lazy-initialization mode | 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啟動時去創(chuàng)建一個 bean 實例。 |
initialization 方法 | 在 bean 的所有必需的屬性被容器設置之后,調用回調方法。它將會在 bean 的生命周期章節(jié)中進行討論。 |
destruction 方法 | 當包含該 bean 的容器被銷毀時,使用回調方法。它將會在 bean 的生命周期章節(jié)中進行討論。 |
Bean 與 Spring 容器的關系
下圖表達了Bean 與 Spring 容器之間的關系:
Spring IoC 容器完全由實際編寫的配置元數據的格式解耦。有下面三個重要的方法把配置元數據提供給 Spring 容器:
基于 XML 的配置文件
基于注解的配置
提示:對于基于 XML 的配置,Spring 2.0 以后使用 Schema 的格式,使得不同類型的配置擁有了自己的命名空間,使配置文件更具擴展性。
你已經看到了如何把基于 XML 的配置元數據提供給容器,但是讓我們看看另一個基于 XML 配置文件的例子,這個配置文件中有不同的 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-3.0.xsd">
<!-- A simple bean definition -->
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with lazy init set on -->
<bean id="..." class="..." lazy-init="true">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with initialization method -->
<bean id="..." class="..." init-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- A bean definition with destruction method -->
<bean id="..." class="..." destroy-method="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
在上述示例中:
①xmlns="http://www.springframework.org/schema/beans",默認命名空間:它沒有空間名,用于Spring Bean的定義;
②xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",xsi命名空間:這個命名空間用于為每個文檔中命名空間指定相應的Schema樣式文件,是標準組織定義的標準命名空間。
你可以查看 Spring Hello World 實例 來詳細理解如何定義,配置和創(chuàng)建 Spring Beans。
關于基于注解的配置將在一個單獨的章節(jié)中進行討論??桃獍阉A粼谝粋€單獨的章節(jié),是因為我想讓你在開始使用注解和 Spring 依賴注入編程之前,能掌握一些其他重要的 Spring 概念。
更多建議: