javascript
SpringBoot @PostConstruct和@PreDestroy使用详解
1. @PostConstruct
1.1 概述
@PostConstruct標記在方法上,在當前類的實例加入到容器之前,會先執行@PostConstruct標記的方法。它的執行順序是這樣的:
- 先執行當前類的構造函數
- 然后執行@Autowired標記對象的初始化
- 最后執行@PostConstruct標記的方法
- 如果沒有拋出異常,則該對象加入Spring管理容器
1.2 驗證執行順序
創建一個空的Spring Boot項目,這步不演示了
創建TestComponent
創建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,加入引用MyService
@Autowiredprivate MyService myService;再執行一下,看看結果有什么變化
TestComponent 構造函數 MyServiceImpl 構造函數 MyServiceImpl PostConstruct TestComponent PostConstructMyServiceImpl執行順序往前移動了,證明@Autowired順序在@PostConstruct之前
因此,如果要在TestComponent初始化的時候調用MyService方法,要寫在@PostConstruct內部,不能在構造函數處理(這時候MyServiceImpl還沒初始化,會拋出空指針異常)
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使用详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot使用CommandL
- 下一篇: Java进阶:多线程Lock管理多个Co