Spring之旅-Bean生命週期-2020-1-22

Spring容器使用DI管理組件,它有兩種類型(接口)。
bean工廠(最基本容器)
import org.springframework.beans.factory.BeanFactory;
應用上下文(開發使用)
import org.springframework.context.ApplicationContext;web

經常使用的應用上下文有:
Java配置Spring應用上下文。
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
Java配置SpringWeb應用上下文。
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
類路徑下XML配置文件加載應用上下文,把定義文件做爲類資源。
import org.springframework.context.support.ClassPathXmlApplicationContext;
系統路徑下XML配置文件加載應用上下文。
import org.springframework.context.support.FileSystemXmlApplicationContext;
Web應用下XML配置文件加載應用上下文
import org.springframework.web.context.support.XmlWebApplicationContext;spring

Bean的生命週期。
1,bean實例化,建立。
2,將值和bean的引用注入到bean屬性中。
3,若是bean實現BeanNameAware接口,將bean的ID傳遞給setBean-Name()方法。
4,若是bean實現了BeanFactoryAweare接口,調用setBeanFactory()方法,將BeanFactory容器實例傳入。
5,若是bean實現ApplicationContextAware接口,調用setApplicationContext()方法,將bean所在應用上下文的引用傳入。
6,若是bean實現BeanPostProcessor接口,調用PostProcessorBeforeInitialization()方法。(預初始化)
7,若是bean實現InitializaingBean接口,調用afterPropertiesSet()方法。
8,若是bean實現BeanPostProcessor接口,調用PostProcessorAfterInitialization()方法。(初始化後)
9,bean可使用了。
10,若是bean實現DisposableBean接口,調用destroy()接口方法,銷燬。接口

相關文章
相關標籤/搜索