首先介紹一下BeanFacory和ApplicationContext的區(qū)別。
它們都能創(chuàng)建IOC容器,但還有有些區(qū)別。
BeanFactory
BeanFactory是Spring中最底層的接口,提供了最簡(jiǎn)單的容器的功能,它有很多具體的實(shí)現(xiàn)類,例如:
DefaultListableBeanFactory、XmlBeanFactory和ApplicationContext。沒錯(cuò),ApplicationContext也是它的子類,繼承了它的所有功能,并額外擴(kuò)展了其他功能。
BeanFactory接口設(shè)計(jì)了getBean方法,可以取得Ioc容器中管理的bean。
public interface BeanFactory {
/**
* Used to dereference a {@link FactoryBean} instance and distinguish it from
* beans <i>created</i> by the FactoryBean. For example, if the bean named
* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
* will return the factory, not the instance returned by the factory.
*/
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
從接口定義的方法可以看出,它主要可以做下面幾件事:
- 通過接口方法containsBean讓用戶能夠判斷容器是否含有指定名字的Bean
- 通過接口方法isSingleton來查詢指定名字的Bean是否是Singleton類型的Bean。
- 通過接口方法isPrototype來查詢指定名字的bean是否是prototype類型
- 通過接口方法getTpye來查詢指定名字的bean的class類型
- 通過接口方法getAliases來查詢指定了名字的Bean的所有別名
BeanFactory在啟動(dòng)的時(shí)候不會(huì)去實(shí)例化bean, 等需要的時(shí)候才會(huì)到容器中去實(shí)例化。
ApplicationContext
ApplicationContext是一個(gè)高級(jí)形態(tài)意義的IOC容器,是在BeanFactory的基礎(chǔ)上添加額外功能。
- 支持不同的信息源。因?yàn)樗鼣U(kuò)展了MessageSource接口,可以支持國(guó)際化的實(shí)現(xiàn)。
- 訪問資源,這一特性體現(xiàn)在對(duì)ResourceLoader和Resource的支持上,可以從不同的地方得到Bean定義資源。
- 支持應(yīng)用事件,消息發(fā)送,響應(yīng)機(jī)制。
- AOP(攔截器)
- 載入多個(gè)(有繼承關(guān)系)上下文 ,使得每一個(gè)上下文都專注于一個(gè)特定的層次,比如應(yīng)用的web層
ApplicationContext在啟動(dòng)的時(shí)候會(huì)加載非懶加載的單例bean,其它的類型只有在需要的時(shí)候才會(huì)被加載。
bean的一生
bean的生命周期可以分為下面幾步:
- 實(shí)例化bean對(duì)象(通過構(gòu)造方法或工廠方法)
- 設(shè)置對(duì)象屬性(setter等)(依賴注入)
- 如果bean實(shí)現(xiàn)了BeanNameAware接口,工廠調(diào)用Bean的setBeanName方法傳遞Bean的ID,就是讓實(shí)現(xiàn)這個(gè)接口的bean知道自己在Spring容器的名字。
- 如果bean實(shí)現(xiàn)了BeanFactoryAware接口,工廠調(diào)用setBeanFactory方法傳入工廠自身,讓bean獲取配置自己的工廠。
- 將Bean實(shí)例傳遞給Bean的前置處理器的postProcessBeforeInitialization(Object bean, String beanname)方法。
- 調(diào)用Bean的初始化方法
- 將Bean實(shí)例傳遞給Bean的后置處理器的postProcessAfterInitialization(Object bean, String beanname)方法
- 使用bean
- 是否實(shí)現(xiàn)DisposableBean接口
- 容器關(guān)閉之前,調(diào)用Bean的銷毀方法。
InitializingBean
InitializingBean的作用是在bean初始化后執(zhí)行定制化的操作
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
接口只有一個(gè)方法afterPropertiesSet,此方法的調(diào)用入口是負(fù)責(zé)加載 spring bean 的AbstractAutowireCapableBeanFactory,源碼如下:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
從這段源碼可以得出以下結(jié)論:
- spring為bean提供了兩種初始化bean的方式,實(shí)現(xiàn)InitializingBean接口,實(shí)現(xiàn)afterPropertiesSet方法,或者在配置文件中通過init-method指定,兩種方式可以同時(shí)使用
- 實(shí)現(xiàn)InitializingBean接口是直接調(diào)用afterPropertiesSet方法,比通過反射調(diào)用init-method指定的方法效率相對(duì)來說要高點(diǎn)。但是init-method方式消除了對(duì)spring的依賴
- 先調(diào)用afterPropertiesSet,再執(zhí)行 init-method 方法,如果調(diào)用afterPropertiesSet方法時(shí)出錯(cuò),則不調(diào)用init-method指定的方法。
該方法較適用分布式項(xiàng)目數(shù)據(jù)庫(kù)
DisposableBean
public interface DisposableBean {
void destroy() throws Exception;
}
只定義了一個(gè)方法,destroy,看名字應(yīng)該是對(duì)象在銷毀時(shí)執(zhí)行的。
在對(duì)象銷毀的時(shí)候,會(huì)去調(diào)用DisposableBean的destroy方法。
同樣,在對(duì)象銷毀有一個(gè)參數(shù)配置destroy-method,和init-method相同,在調(diào)用銷毀的時(shí)候,先執(zhí)行 DisposableBean的destroy方法,后執(zhí)行 destroy-method聲明的方法。
BeanFactoryPostProcessor與BeanPostProcessor的區(qū)別
BeanFactoryPostProcessor: BeanFactory后置處理器,是對(duì)BeanDefinition對(duì)象進(jìn)行修改
BeanFactoryPostProcessor接口是針對(duì)bean容器的,它的實(shí)現(xiàn)類可以在當(dāng)前BeanFactory初始化后,bean實(shí)例化之前修改bean的定義屬性。
Spring允許BeanFactoryPostProcessor在容器實(shí)例化其他bean之前讀取配置元數(shù)據(jù),并可以根據(jù)需要進(jìn)行修改,例如把bean的scope從singleton改為prototype,也可以把property的值修改掉。BeanPostProcessor: Bean后置處理器,是對(duì)生成的bean對(duì)象進(jìn)行修改
public interface BeanPostProcessor {
//bean初始化之前調(diào)用
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
//bean初始化之后調(diào)用
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
BeanPostProcessor能在spring容器實(shí)例化bean之后,在執(zhí)行bean的初始化方法前后,添加一些自己的處理邏輯。初始化方法包括以下兩種:
- 實(shí)現(xiàn)InitializingBean接口的bean,對(duì)應(yīng)方法為afterPropertiesSet
- xml定義中,通過init-method設(shè)置的方法
BeanPostProcessor是BeanFactoryProcessor之后執(zhí)行的。
title: Spring之bean的生命周期及一些關(guān)于bean的知識(shí)總結(jié)
首先介紹一下BeanFacory和ApplicationContext的區(qū)別。
它們都能創(chuàng)建IOC容器,但還有有些區(qū)別。
BeanFactory
BeanFactory是Spring中最底層的接口,提供了最簡(jiǎn)單的容器的功能,它有很多具體的實(shí)現(xiàn)類,例如:
DefaultListableBeanFactory、XmlBeanFactory和ApplicationContext。沒錯(cuò),ApplicationContext也是它的子類,繼承了它的所有功能,并額外擴(kuò)展了其他功能。
BeanFactory接口設(shè)計(jì)了getBean方法,可以取得Ioc容器中管理的bean。
public interface BeanFactory {
/**
* Used to dereference a {@link FactoryBean} instance and distinguish it from
* beans <i>created</i> by the FactoryBean. For example, if the bean named
* {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
* will return the factory, not the instance returned by the factory.
*/
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String name) throws BeansException;
<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
boolean containsBean(String name);
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
從接口定義的方法可以看出,它主要可以做下面幾件事:
- 通過接口方法containsBean讓用戶能夠判斷容器是否含有指定名字的Bean
- 通過接口方法isSingleton來查詢指定名字的Bean是否是Singleton類型的Bean。
- 通過接口方法isPrototype來查詢指定名字的bean是否是prototype類型
- 通過接口方法getTpye來查詢指定名字的bean的class類型
- 通過接口方法getAliases來查詢指定了名字的Bean的所有別名
BeanFactory在啟動(dòng)的時(shí)候不會(huì)去實(shí)例化bean, 等需要的時(shí)候才會(huì)到容器中去實(shí)例化。
ApplicationContext
ApplicationContext是一個(gè)高級(jí)形態(tài)意義的IOC容器,是在BeanFactory的基礎(chǔ)上添加額外功能。
- 支持不同的信息源。因?yàn)樗鼣U(kuò)展了MessageSource接口,可以支持國(guó)際化的實(shí)現(xiàn)。
- 訪問資源,這一特性體現(xiàn)在對(duì)ResourceLoader和Resource的支持上,可以從不同的地方得到Bean定義資源。
- 支持應(yīng)用事件,消息發(fā)送,響應(yīng)機(jī)制。
- AOP(攔截器)
- 載入多個(gè)(有繼承關(guān)系)上下文 ,使得每一個(gè)上下文都專注于一個(gè)特定的層次,比如應(yīng)用的web層
ApplicationContext在啟動(dòng)的時(shí)候會(huì)加載非懶加載的單例bean,其它的類型只有在需要的時(shí)候才會(huì)被加載。
bean的一生
bean的生命周期可以分為下面幾步:
- 實(shí)例化bean對(duì)象(通過構(gòu)造方法或工廠方法)
- 設(shè)置對(duì)象屬性(setter等)(依賴注入)
- 如果bean實(shí)現(xiàn)了BeanNameAware接口,工廠調(diào)用Bean的setBeanName方法傳遞Bean的ID,就是讓實(shí)現(xiàn)這個(gè)接口的bean知道自己在Spring容器的名字。
- 如果bean實(shí)現(xiàn)了BeanFactoryAware接口,工廠調(diào)用setBeanFactory方法傳入工廠自身,讓bean獲取配置自己的工廠。
- 將Bean實(shí)例傳遞給Bean的前置處理器的postProcessBeforeInitialization(Object bean, String beanname)方法。
- 調(diào)用Bean的初始化方法
- 將Bean實(shí)例傳遞給Bean的后置處理器的postProcessAfterInitialization(Object bean, String beanname)方法
- 使用bean
- 是否實(shí)現(xiàn)DisposableBean接口
- 容器關(guān)閉之前,調(diào)用Bean的銷毀方法。
InitializingBean
InitializingBean的作用是在bean初始化后執(zhí)行定制化的操作
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
接口只有一個(gè)方法afterPropertiesSet,此方法的調(diào)用入口是負(fù)責(zé)加載 spring bean 的AbstractAutowireCapableBeanFactory,源碼如下:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
從這段源碼可以得出以下結(jié)論:
- spring為bean提供了兩種初始化bean的方式,實(shí)現(xiàn)InitializingBean接口,實(shí)現(xiàn)afterPropertiesSet方法,或者在配置文件中通過init-method指定,兩種方式可以同時(shí)使用
- 實(shí)現(xiàn)InitializingBean接口是直接調(diào)用afterPropertiesSet方法,比通過反射調(diào)用init-method指定的方法效率相對(duì)來說要高點(diǎn)。但是init-method方式消除了對(duì)spring的依賴
- 先調(diào)用afterPropertiesSet,再執(zhí)行 init-method 方法,如果調(diào)用afterPropertiesSet方法時(shí)出錯(cuò),則不調(diào)用init-method指定的方法。
該方法較適用分布式項(xiàng)目數(shù)據(jù)庫(kù)
DisposableBean
public interface DisposableBean {
void destroy() throws Exception;
}
只定義了一個(gè)方法,destroy,看名字應(yīng)該是對(duì)象在銷毀時(shí)執(zhí)行的。
在對(duì)象銷毀的時(shí)候,會(huì)去調(diào)用DisposableBean的destroy方法。
同樣,在對(duì)象銷毀有一個(gè)參數(shù)配置destroy-method,和init-method相同,在調(diào)用銷毀的時(shí)候,先執(zhí)行 DisposableBean的destroy方法,后執(zhí)行 destroy-method聲明的方法。
BeanFactoryPostProcessor與BeanPostProcessor的區(qū)別
BeanFactoryPostProcessor: BeanFactory后置處理器,是對(duì)BeanDefinition對(duì)象進(jìn)行修改
BeanFactoryPostProcessor接口是針對(duì)bean容器的,它的實(shí)現(xiàn)類可以在當(dāng)前BeanFactory初始化后,bean實(shí)例化之前修改bean的定義屬性。
Spring允許BeanFactoryPostProcessor在容器實(shí)例化其他bean之前讀取配置元數(shù)據(jù),并可以根據(jù)需要進(jìn)行修改,例如把bean的scope從singleton改為prototype,也可以把property的值修改掉。BeanPostProcessor: Bean后置處理器,是對(duì)生成的bean對(duì)象進(jìn)行修改
public interface BeanPostProcessor {
//bean初始化之前調(diào)用
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
//bean初始化之后調(diào)用
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
BeanPostProcessor能在spring容器實(shí)例化bean之后,在執(zhí)行bean的初始化方法前后,添加一些自己的處理邏輯。初始化方法包括以下兩種:
- 實(shí)現(xiàn)InitializingBean接口的bean,對(duì)應(yīng)方法為afterPropertiesSet
- xml定義中,通過init-method設(shè)置的方法
BeanPostProcessor是BeanFactoryProcessor之后執(zhí)行的。