【spring源碼分析】spring和@PostConstruct注解


@PostConstruct注解好多人以為是Spring提供的。其實是Java自己的注解。

Java中該注解的說明:@PostConstruct該注解被用來修飾一個非靜態的void()方法。被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之后執行,init()方法之前執行。

通常我們會是在Spring框架中使用到@PostConstruct注解 該注解的方法在整個Bean初始化中的執行順序:

Constructor(構造方法) -> @Autowired(依賴注入) -> @PostConstruct(注釋的方法)

 

 

如果一個類用@Service 或 @Component,那么只需要用@PostConstruct修飾某個方法,該方法能在類實例化的過程中自動執行,相當於類的構造函數。同時,具備了構造函數不具備的功能。

@Service
class Test{
@PostConstruct
public void sayHello(){
System.out.println("Hello!");
}
}
但是需要注意:

子類實例化過程中會調用父類中的@PostConstruct方法!
@Service
class TestChild extends Test{
@PostConstruct
public void sayBye(){
System.out.println("Bye!");
}
}
啟動項目,輸出如下:
Hello!
Bye!


免責聲明!

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



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