Spring@PostConstruct注解和構造方法的調用順序


先看下@PostConstruct的注解

 * 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. The method on which the
 * PostConstruct annotation is applied MUST fulfill all of the following
 * criteria -

自己翻譯一下,意思是:

PostConstruct注解用於方法上,該方法在初始化的依賴注入操作之后被執行。這個方法必須在class被放到service之后被執行,這個注解所在的類必須支持依賴注入。

父類class,被@component注解修飾,說明會被spring掃描並創建。在默認構造方法里加上輸出打印,init方法被@PostConstruct修飾

 1 @Component
 2 public class ParentBean implements InitializingBean{
 3     
 4     public ParentBean() {
 5         System.out.println("ParentBean construct");
 6     }
 7     
 8     @PostConstruct
 9     public void init(){
10         System.out.println("ParentBean init");
11     }
12 
13     public void afterPropertiesSet() throws Exception {
14         System.out.println("ParentBean afterPropertiesSet");
15     }
16 
17 }

子類class,也被 @component注解修飾,其余配置和父類class一樣

 1 @Component
 2 public class SonBean extends ParentBean{
 3     public SonBean() {
 4         System.out.println("SonBean construct");
 5     }
 6     
 7     @PostConstruct
 8     public void init(){
 9         System.out.println("SonBean init");
10     }
11     @Override
12     public void afterPropertiesSet() throws Exception {
13         System.out.println("SonBean afterPropertiesSet");
14     }
15     
16 }

然后我們使用maven命令 jetty:run,控制台輸出如下:

[INFO] Initializing Spring root WebApplicationContext
ParentBean construct
ParentBean init
ParentBean afterPropertiesSet
ParentBean construct
SonBean construct
SonBean init
SonBean afterPropertiesSet
[INFO] Set web app root system property: 'webapp.root' = [J:\androidworkspace\com\src\main\webapp\]
[INFO] Initializing log4j from [classpath:log4j.properties]
[INFO] Started SelectChannelConnector@0.0.0.0:8088
[INFO] Started Jetty Server
[INFO] Starting scanner at interval of 3 seconds.

可以看出優先執行依然是構造方法,這個是java的語言決定的,畢竟spring只是建立在java之上的框架。然后才是被PostConstruct修飾的方法,要注意的是這個方法在對象的初始化和依賴都完成之后才會執行,所以不必擔心執行這個方法的時候有個別成員屬性沒有被初始化為null的情況發生。在init方法之后執行的才是afterPropertiesSet方法,這個方法必須實現InitializingBean接口,這個接口很多spring的bean都實現了他,從他的方法名就能看出在屬性都被設置了之后執行,也屬於springbean初始化方法。

其實spring提供了很多接口以供開發者在bean初始化后調用,可以在官網上查閱相關文檔。

參考:https://my.oschina.net/wwwd/blog/810530


免責聲明!

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



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