Spring Bean 定義

2022-05-21 15:21 更新

被稱作 bean 的對象是構(gòu)成應用程序的支柱也是由 Spring IoC 容器管理的。bean 是一個被實例化,組裝,并通過 Spring IoC 容器所管理的對象。這些 bean 是由用容器提供的配置元數(shù)據(jù)創(chuàng)建的,例如,已經(jīng)在先前章節(jié)看到的,在 XML 的表單中的 定義。

bean 定義包含稱為配置元數(shù)據(jù)的信息,下述容器也需要知道配置元數(shù)據(jù):

  • 如何創(chuàng)建一個 bean

  • bean 的生命周期的詳細信息

  • bean 的依賴關(guān)系

上述所有的配置元數(shù)據(jù)轉(zhuǎn)換成一組構(gòu)成每個 bean 定義的下列屬性。

屬性 描述
class 這個屬性是強制性的,并且指定用來創(chuàng)建 bean 的 bean 類。
name 這個屬性指定唯一的 bean 標識符。在基于 XML 的配置元數(shù)據(jù)中,你可以使用 ID 和/或 name 屬性來指定 bean 標識符。
scope 這個屬性指定由特定的 bean 定義創(chuàng)建的對象的作用域,它將會在 bean 作用域的章節(jié)中進行討論。
constructor-arg 它是用來注入依賴關(guān)系的,并會在接下來的章節(jié)中進行討論。
properties 它是用來注入依賴關(guān)系的,并會在接下來的章節(jié)中進行討論。
autowiring mode 它是用來注入依賴關(guān)系的,并會在接下來的章節(jié)中進行討論。
lazy-initialization mode 延遲初始化的 bean 告訴 IoC 容器在它第一次被請求時,而不是在啟動時去創(chuàng)建一個 bean 實例。
initialization 方法 在 bean 的所有必需的屬性被容器設(shè)置之后,調(diào)用回調(diào)方法。它將會在 bean 的生命周期章節(jié)中進行討論。
destruction 方法 當包含該 bean 的容器被銷毀時,使用回調(diào)方法。它將會在 bean 的生命周期章節(jié)中進行討論。

Bean 與 Spring 容器的關(guān)系

下圖表達了Bean 與 Spring 容器之間的關(guān)系:

Spring Bean

Spring 配置元數(shù)據(jù)

Spring IoC 容器完全由實際編寫的配置元數(shù)據(jù)的格式解耦。有下面三個重要的方法把配置元數(shù)據(jù)提供給 Spring 容器:

  • 基于 XML 的配置文件

  • 基于注解的配置

  • 基于 Java 的配置

提示:對于基于 XML 的配置,Spring 2.0 以后使用 Schema 的格式,使得不同類型的配置擁有了自己的命名空間,使配置文件更具擴展性。

你已經(jīng)看到了如何把基于 XML 的配置元數(shù)據(jù)提供給容器,但是讓我們看看另一個基于 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。

關(guān)于基于注解的配置將在一個單獨的章節(jié)中進行討論??桃獍阉A粼谝粋€單獨的章節(jié),是因為我想讓你在開始使用注解和 Spring 依賴注入編程之前,能掌握一些其他重要的 Spring 概念。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號