Spring@PostConstruct和@PreDestroy注解詳解


 

@PostConstruct注解使用

@PostConstructApi使用說明

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected. Only one method can be annotated with this annotation

PostConstruct批注用於需要依賴注入完成以執行任何初始化之后需要執行的方法上。在類投入使用之前必須調用此方法。所有支持依賴注入的類都必須支持該注釋。即使該類不要求注入任何資源,也必須調用用PostConstruct注釋的方法。此注釋只能注釋一種方法

@PostConstruct的注意事項有:

  • 除了攔截器的情況外,該方法不得具有任何參數,在這種情況下,該方法將采用Interceptors規范定義的InvocationContext對象

  • 在攔截器里定義的方法必須滿足下面兩種方式

    • void (InvocationContext)
    • Object (InvocationContext) throws Exception
  • 在非攔截器里定義的方法必須滿足這種形式

    • void ()
  • 應用PostConstruct的方法可以用public,protected,package private 或private 修飾。

  • 除了應用程序客戶端,該方法一定不能是靜態的

  • 方法可能是用final修飾的

  • 如果該方法拋出未經檢查的異常,則該類不得投入使用,除非在EJB可以處理異常甚至從異常中恢復的EJB情況下

SpringBean 的初始化流程

st=>start: 開始
op1=>operation: Spring容器加載
op2=>operation: 調用構造函數
op3=>operation: @PostConstruct方法調用
op4=>operation: init()調用
op5=>operation: 其他代碼
op6=>operation: destroy()調用
op7=>operation: @PreDestroy方法調用
e=>end: 結束

st->op1->op2->op3->op4->op5->op6->op7->e

@PostConstruct方法是在init()方法之前構造方法調用之后執行的

項目應用場景

一般用於一些系統配置或者緩存數據的加載。

@PreDestroy注解

The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding. This annotation MUST be supported by all container managed objects that support PostConstruct except the application client container in Java EE 5

@PreDestroy 注解在方法上用作回調通知,以表明實例正在被容器刪除。帶有@PreDestroy 注解的方法通常用於釋放它一直持有的資源。除Java EE 5中的應用程序客戶端容器外,所有支持PostConstruct的容器管理對象都必須支持此注釋。

@PreDestroy的注意事項有:

  • 除了攔截器的情況外,該方法不得具有任何參數,在這種情況下,該方法將采用Interceptors規范定義的InvocationContext對象

  • 在攔截器里定義的方法必須滿足下面兩種方式

    • void (InvocationContext)
    • Object (InvocationContext) throws Exception
  • 在非攔截器里定義的方法必須滿足這種形式

    • void ()
  • 應用@PreDestroy注解的方法可以用public,protected,package private 或private 修飾。

  • 該方法一定不能是靜態的

  • 方法可能是用final修飾的

  • 如果該方法拋出未經檢查的異常,則該類不得投入使用,除非在EJB可以處理異常甚至從異常中恢復的EJB情況下

使用實例:

public Class XXX {

    @Autowired

    private YYY y;



    public XXX() {

        System.out.println("此時y還未被注入: y = " + y);

    }

    @PostConstruct

    private void init() {

        System.out.println("@PostConstruct將在依賴注入完成后被自動調用: y = " + y);

    }
  
   @Predestory

    private void preDestory() {

        System.out.println("XXX 正在被容器刪除");

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM