1. 程式人生 > >Spring例項化時各種初始化方法執行順序

Spring例項化時各種初始化方法執行順序

帶序號的步驟來自Spring實戰(第4版),紅字為補充部分。

1.Spring對bean進行例項化;

Constructor構造方法

2.Spring將值和bean的引用注入到bean對應的屬性中;
3.如果bean實現了BeanNameAware介面,Spring將bean的ID傳遞給setBean-Name()方法;
4.如果bean實現了BeanFactoryAware介面,Spring將呼叫setBeanFactory()方法,將BeanFactory容器例項傳入;
5.如果bean實現了ApplicationContextAware介面,Spring將呼叫setApplicationContext()方法,將bean所在的應用上下文的引用傳入進來;
6.如果bean實現了BeanPostProcessor介面,Spring將呼叫它們的post-ProcessBeforeInitialization()方法;

@PostConstruct,不是spring的一部分,來自rt.jar的註解。

7.如果bean實現了InitializingBean介面,Spring將呼叫它們的after-PropertiesSet()方法。類似地,如果bean使用initmethod聲明瞭初始化方法,該方法也會被呼叫;

<bean init-method/>

8.如果bean實現了BeanPostProcessor介面,Spring將呼叫它們的post-ProcessAfterInitialization()方法;

ApplicationListener<ContextRefreshedEvent>.onApplicationEvent

9.此時,bean已經準備就緒,可以被應用程式使用了,它們將一直駐留在應用上下文中,直到該應用上下文被銷燬;
10.如果bean實現了DisposableBean介面,Spring將呼叫它的destroy()介面方法。同樣,如果bean使用destroy-method聲明瞭銷燬方法,該方法也會被呼叫。


另外,單例模式下實現BeanPostProcessor介面的bean不呼叫實現方法;實現該介面的類也不會呼叫實現方法,並且Spring會先初始化該類。
參考:https://ask.csdn.net/questions/679699