bean的定義
形成應用程序的骨干是由Spring IoC容器所管理的對象稱為bean。bean被實例化,組裝,并通過Spring IoC容器所管理的對象。這些bean由容器提供,例如,在XML的<bean/>定義,已經看到了前幾章的形式配置元數據創(chuàng)建。
bean定義包含所需要的容器要知道以下稱為配置元數據的信息:
上述所有配置元數據轉換成一組的下列屬性構成每個bean的定義。
Spring配置元數據
Spring IoC容器完全由在此配置元數據實際寫入的格式解耦。有下列提供的配置元數據的Spring容器三個重要的方法:
我們已經看到了基于XML的配置元數據如何提供給容器,但讓我們看到了不同的bean定義,包括延遲初始化,初始化方法和銷毀方法基于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-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>
bean的生命周期
Spring bean的生命周期是很容易理解。當一個bean實例化時,它可能需要執(zhí)行一些初始化把它轉換成可用狀態(tài)。類似地,當bean不再需要,并且從容器中取出,一些清理的工作可能也需要做。
不過,還有把bean背后的實例化和銷毀時間之間的場景發(fā)生的活動,但是本章將只討論其中兩個是需要在bean的初始化和銷毀的時候,重要bean的生命周期回調方法。
要定義安裝和拆卸一個bean,我們只是聲明了初始化方法和/或銷毀,方法的參數<bean>。在init-method屬性指定一個方法,是被調用bean后立即實例化。同樣,銷毀方法規(guī)定了被調用當bean被從容器中取出之前的方法。
初始化回調:
org.springframework.beans.factory.InitializingBean 接口指定一個單一的方法:
void afterPropertiesSet() throws Exception;
因此,可以簡單地實現上述接口和初始化工作可以在里面afterPropertiesSet() 方法,如下所示:
public class ExampleBean implements InitializingBean { public void afterPropertiesSet() { // do some initialization work }}
在基于XML的配置元數據的情況下,可以使用init-method 屬性來指定具有void無參數簽名的方法的名稱。例如:
<bean id="exampleBean" class="examples.ExampleBean" init-method="init"/>
下面是類的定義:
public class ExampleBean { public void init() { // do some initialization work }}
銷毀回調
org.springframework.beans.factory.DisposableBean接口指定一個單一的方法:
void destroy() throws Exception;
因此,你可以簡單地實現上述接口和定稿工作可以做里面的destroy() 方法,如下所示:
public class ExampleBean implements DisposableBean { public void destroy() { // do some destruction work }}
在基于XML的配置元數據的情況下,您可以使用destroy-method屬性來指定具有void無參數簽名的方法的名稱。例如:
<bean id="exampleBean" class="examples.ExampleBean" destroy-method="destroy"/>
下面是類的定義:
public class ExampleBean { public void destroy() { // do some destruction work }}
如果您在非web應用環(huán)境中使用Spring的IoC容器,例如在桌面富客戶端環(huán)境; 注冊關閉鉤子在JVM中。這樣做可以確保正常關機,并讓所有的資源都被釋放調用singleton bean上的相關destroy方法。
建議不要使用的InitializingBean或者DisposableBean的回調,因為XML配置提供極大的靈活性在命名你的方法方面。
例如:
使用Eclipse IDE,然后按照下面的步驟來創(chuàng)建一個Spring應用程序:
新聞熱點
疑難解答