1. 程式人生 > 其它 >Spring深入淺出(二),3種方法實現Bean初始化回撥(含Spring中@PostConstruct註解的配置)

Spring深入淺出(二),3種方法實現Bean初始化回撥(含Spring中@PostConstruct註解的配置)

一、使用介面實現Bean初始化回撥

org.springframework.beans.factory.InitializingBean 介面提供了以下方法:

void afterPropertiesSet() throws Exception;

實現程式碼如下:

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("其次,呼叫InitializingBean的 afterPropertiesSet方法......");
    }

二、 配置XML實現Bean初始化回撥

可以通過 init-method 屬性指定 Bean 初始化後執行的方法。

    <bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" scope="prototype" init-method="init2">
        <property name="message" value="Hello World!" />
    </bean>

同時加入實現程式碼:

    public void init2() {
        System.out.println("最後,呼叫XML配置檔案中指定的初始化方式......");
    }

三、 使用註解實現Bean初始化回撥

使用@PostConstruct 註解標明該方法為 Bean 初始化後的方法。

    @PostConstruct
    public void init1() {
        System.out.println("最先呼叫@PostConstruct方式的初始化方法......" );
    }    

四、@PostConstruct註解的配置

1. 在配置檔案中使用 context 名稱空間之前,必須在 <beans> 元素中宣告 context 名稱空間

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

2. 然後才是引用

<context:annotation-config/>

3. 需要在專案中引用若干Spring包

包括但不限於:commons-logging-1.2.jar,以及常用Spring包。

五、全部程式碼參考如下

1 .實體Bean

View Code

2. 呼叫者

View Code

3. Bean.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" scope="prototype" init-method="init2">
        <property name="message" value="Hello World!" />
    </bean>
    <context:annotation-config/>
</beans>

六、輸出如下

另:銷燬回撥同樣有三種方式

1. 實現org.springframework.beans.factory.DisposableBean 介面的destroy()方法

2. 配置XML檔案,設定destroy-method 屬性指定 Bean 銷燬後執行的方法

3.使用@PreDestory 註解標明該方法為 Bean 銷燬前執行的方法

本文參考:

http://c.biancheng.net/spring/bean-life-cycle.html