日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

SpringBoot @PostConstruct和@PreDestroy使用详解

發布時間:2025/3/19 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot @PostConstruct和@PreDestroy使用详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. @PostConstruct

1.1 概述

@PostConstruct標記在方法上,在當前類的實例加入到容器之前,會先執行@PostConstruct標記的方法。它的執行順序是這樣的:

  • 先執行當前類的構造函數
  • 然后執行@Autowired標記對象的初始化
  • 最后執行@PostConstruct標記的方法
  • 如果沒有拋出異常,則該對象加入Spring管理容器

1.2 驗證執行順序

創建一個空的Spring Boot項目,這步不演示了


創建TestComponent

@Component public class TestComponent {public TestComponent(){System.out.println("TestComponent 構造函數");}@PostConstructpublic void init(){System.out.println("TestComponent PostConstruct");} }

創建MyService

public interface MyService {void Hello(String name); }

創建MyServiceImpl

@Service public class MyServiceImpl implements MyService {public MyServiceImpl(){System.out.println("MyServiceImpl 構造函數");}@PostConstructpublic void init(){System.out.println("MyServiceImpl PostConstruct");}@Overridepublic void Hello(String name) {System.out.println("Hello " + name);} }

運行項目,看下輸出結果。
TestComponent和MyServiceImpl分別獨自初始化,構造函數優先執行
請記住這個執行順序

TestComponent 構造函數 TestComponent PostConstruct MyServiceImpl 構造函數 MyServiceImpl PostConstruct

還沒完,改一下TestComponent,加入引用MyService

@Autowiredprivate MyService myService;

再執行一下,看看結果有什么變化

TestComponent 構造函數 MyServiceImpl 構造函數 MyServiceImpl PostConstruct TestComponent PostConstruct

MyServiceImpl執行順序往前移動了,證明@Autowired順序在@PostConstruct之前


因此,如果要在TestComponent初始化的時候調用MyService方法,要寫在@PostConstruct內部,不能在構造函數處理(這時候MyServiceImpl還沒初始化,會拋出空指針異常)

@Component public class TestComponent {@Autowiredprivate MyService myService;public TestComponent(){System.out.println("TestComponent 構造函數");//寫在這里必定拋出異常,此時 myService == null//myService.Hello("張三");}@PostConstructpublic void init(){System.out.println("TestComponent PostConstruct");//在這里調用MySerice方法才正確myService.Hello("張三");} }

2. @PreDestroy

首先,來看下Java Doc對這個注解的說明


1: 在對象實例被容器移除的時候,會回調調用@PreDestroy標記的方法
2: 通常用來釋放該實例占用的資源

修改上面的TestComponent代碼,加上@PreDestroy代碼

@PreDestroypublic void destroy(){System.out.println("TestComponent 對象被銷毀了");}

修改Application main方法,啟動10秒后退出程序

@SpringBootApplication public class AnnotationTestApplication {public static void main(String[] args) {ConfigurableApplicationContext ctx = SpringApplication.run(AnnotationTestApplication.class, args);try {Thread.sleep(10 * 1000);} catch (InterruptedException e) {e.printStackTrace();}ctx.close();} }

啟動程序,查看輸出信息
程序退出時會銷毀對象,所以會觸發我們剛寫的@PreDestroy方法,測試通過。

總結

以上是生活随笔為你收集整理的SpringBoot @PostConstruct和@PreDestroy使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。