spring@PostConstruct註解和構造方法的調用順序

 

先看下@PostConstruct的註解java

* 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 -

本身翻譯一下,意思是:android

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

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

@Component
public class ParentBean implements InitializingBean{
	
	public ParentBean() {
		System.out.println("ParentBean construct");
	}
	
	@PostConstruct
	public void init(){
		System.out.println("ParentBean init");
	}

	public void afterPropertiesSet() throws Exception {
		System.out.println("ParentBean afterPropertiesSet");
	}

}

子類class,也被 @component註解修飾,其他配置和父類class同樣app

@Component
public class SonBean extends ParentBean{
	public SonBean() {
		System.out.println("SonBean construct");
	}
	
	@PostConstruct
	public void init(){
		System.out.println("SonBean init");
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("SonBean afterPropertiesSet");
	}
	
}

而後咱們使用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初始化方法。webapp

其實spring提供了不少接口以供開發者在bean初始化後調用,能夠在官網上查閱相關文檔。maven

相關文章
相關標籤/搜索