Spring--Bean初始化和銷毀前的操作順序

Spring 允許在 Bean 在初始化完成后以及 Bean 銷毀前執(zhí)行特定的操作,常用的設定方式有以下三種:

  1. 通過Bean實現 InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;【缺點:要依賴Spring】

  2. 通過 <bean> 元素的 init-method/destroy-method屬性指定初始化之后 /銷毀之前調用的操作方法;(也可以不是xml配置,而是在@Bean上注解,效果相同)【優(yōu)點:不依賴于Spring的接口】

  3. 在指定方法上加上@PostConstruct 或@PreDestroy 注解來制定該方法是在初始化之后還是銷毀之前調用【在servlet中,要考慮的執(zhí)行流程是:servlet構造函數 > PostConstruct > init() > service() > destory() > PreDestroy】

注意:子類實例化過程中會調用父類中的@PostConstruct方法!

但他們之前并不等價。即使3個方法都用上了,也有先后順序.

Bean在實例化的過程中:Constructor > @PostConstruct >InitializingBean > init-method
Bean在銷毀的過程中:@PreDestroy > DisposableBean > destroy-method
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class InitAndDestroySeqBean implements InitializingBean,DisposableBean {

    public InitAndDestroySeqBean(){
        System.out.println("執(zhí)行InitAndDestroySeqBean: 構造方法");
    }
    
    @PostConstruct
    public void postConstruct() {  
       System.out.println("執(zhí)行InitAndDestroySeqBean: postConstruct");  
    }  
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("執(zhí)行InitAndDestroySeqBean: afterPropertiesSet"); 
    }
    
    public void initMethod() {
        System.out.println("執(zhí)行InitAndDestroySeqBean: init-method");
    }

    @PreDestroy
    public void preDestroy()  {
        System.out.println("執(zhí)行InitAndDestroySeqBean: preDestroy");
    }
    
    @Override
    public void destroy() throws Exception {
        System.out.println("執(zhí)行InitAndDestroySeqBean: destroy");
    }
    
    public void destroyMethod() {
        System.out.println("執(zhí)行InitAndDestroySeqBean: destroy-method");
    }
    
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("com/chj/spring/bean.xml");
        context.close();
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
     xmlns:context="http://www.springframework.org/schema/context"  
     xsi:schemaLocation="http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
 
   <context:annotation-config/>  
   
   <bean id="initAndDestroySeqBean" class="com.chj.spring.InitAndDestroySeqBean" init-method="initMethod" destroy-method="destroyMethod"/>
</beans>
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容