1. @PostConstruct
1.1 概述
@PostConstruct標(biāo)記在方法上,在當(dāng)前類的實(shí)例加入到容器之前,會(huì)先執(zhí)行@PostConstruct標(biāo)記的方法。它的執(zhí)行順序是這樣的:
- 先執(zhí)行當(dāng)前類的構(gòu)造函數(shù)
- 然后執(zhí)行@Autowired標(biāo)記對(duì)象的初始化
- 最后執(zhí)行@PostConstruct標(biāo)記的方法
- 如果沒(méi)有拋出異常,則該對(duì)象加入Spring管理容器
1.2 驗(yàn)證執(zhí)行順序
創(chuàng)建一個(gè)空的Spring Boot項(xiàng)目,這步不演示了
創(chuàng)建TestComponent
@Component public class TestComponent { public TestComponent(){ System.out.println("TestComponent 構(gòu)造函數(shù)"); } @PostConstruct public void init(){ System.out.println("TestComponent PostConstruct"); } }
創(chuàng)建MyService
public interface MyService { void Hello(String name); }
創(chuàng)建MyServiceImpl
@Service public class MyServiceImpl implements MyService { public MyServiceImpl(){ System.out.println("MyServiceImpl 構(gòu)造函數(shù)"); } @PostConstruct public void init(){ System.out.println("MyServiceImpl PostConstruct"); } @Override public void Hello(String name) { System.out.println("Hello " + name); } }
運(yùn)行項(xiàng)目,看下輸出結(jié)果。
TestComponent和MyServiceImpl分別獨(dú)自初始化,構(gòu)造函數(shù)優(yōu)先執(zhí)行
請(qǐng)記住這個(gè)執(zhí)行順序
TestComponent 構(gòu)造函數(shù)
TestComponent PostConstruct
MyServiceImpl 構(gòu)造函數(shù)
MyServiceImpl PostConstruct
還沒(méi)完,改一下TestComponent,加入引用MyService
@Autowired private MyService myService;
再執(zhí)行一下,看看結(jié)果有什么變化
TestComponent 構(gòu)造函數(shù)
MyServiceImpl 構(gòu)造函數(shù)
MyServiceImpl PostConstruct
TestComponent PostConstruct
MyServiceImpl執(zhí)行順序往前移動(dòng)了,證明@Autowired順序在@PostConstruct之前
因此,如果要在TestComponent初始化的時(shí)候調(diào)用MyService方法,要寫在@PostConstruct內(nèi)部,不能在構(gòu)造函數(shù)處理(這時(shí)候MyServiceImpl還沒(méi)初始化,會(huì)拋出空指針異常)
@Component public class TestComponent { @Autowired private MyService myService; public TestComponent(){ System.out.println("TestComponent 構(gòu)造函數(shù)"); //寫在這里必定拋出異常,此時(shí) myService == null //myService.Hello("張三"); } @PostConstruct public void init(){ System.out.println("TestComponent PostConstruct"); //在這里調(diào)用MySerice方法才正確 myService.Hello("張三"); } }
2. @PreDestroy
首先,來(lái)看下Java Doc對(duì)這個(gè)注解的說(shuō)明
1: 在對(duì)象實(shí)例被容器移除的時(shí)候,會(huì)回調(diào)調(diào)用@PreDestroy標(biāo)記的方法
2: 通常用來(lái)釋放該實(shí)例占用的資源
修改上面的TestComponent代碼,加上@PreDestroy代碼
@PreDestroy public void destroy(){ System.out.println("TestComponent 對(duì)象被銷毀了"); }
修改Application main方法,啟動(dòng)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(); } }
啟動(dòng)程序,查看輸出信息
程序退出時(shí)會(huì)銷毀對(duì)象,所以會(huì)觸發(fā)我們剛寫的@PreDestroy方法,測(cè)試通過(guò)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_28834355/article/details/109206067