Spring實例化時各類初始化方法執行順序

帶序號的步驟來自Spring實戰(第4版),其餘爲補充部分。spring

1.Spring對bean進行實例化;post

Constructor構造方法.net

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的註解。get

7.若是bean實現了InitializingBean接口,Spring將調用它們的after-PropertiesSet()方法。相似地,若是bean使用initmethod聲明瞭初始化方法,該方法也會被調用;it

<bean init-method/>io

8.若是bean實現了BeanPostProcessor接口,Spring將調用它們的post-ProcessAfterInitialization()方法;容器

ApplicationListener<ContextRefreshedEvent>.onApplicationEventList

9.此時,bean已經準備就緒,能夠被應用程序使用了,它們將一直駐留在應用上下文中,直到該應用上下文被銷燬; 10.若是bean實現了DisposableBean接口,Spring將調用它的destroy()接口方法。一樣,若是bean使用destroy-method聲明瞭銷燬方法,該方法也會被調用。sso

另外,單例模式下實現BeanPostProcessor接口的bean不調用實現方法;實現該接口的類也不會調用實現方法,而且Spring會先初始化該類。 參考:ask.csdn.net/questions/6…

相關文章
相關標籤/搜索