2、Bean的生命周期
Spring Bean的完整生命周期从创建Spring容器开始,直到最终Spring容器销毁Bean。大致流程如下:
2.1 BeanFactoryPostProcessor
中文名为:BeanFactory后置处理器。就是可以管理我们的Bean工厂的BeanDefinition(还未实例化)数据,可以修改BeanDefinition的属性(例如从单例修改为多例)。是Bean生命周期最先开始的类。
BeanFactoryPostProcessor的实现脑图:
使用方法:
public class BeanFactoryProcessorTest implements BeanFactoryPostProcessor {
/**
* 主要用来修改BeanFactory已经持有的BeanDefinition
* ConfigurableListableBeanFactory其实就是DefaultListableBeanFactory对象
*/
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("调用了BeanFactoryPostProcessor");
//后面是获得所有BeanDefinition。
String[] name = beanFactory.getBeanDefinitionNames();
for(String s : name){
BeanDefinition bd = beanFactory.getBeanDefinition(s);
System.out.println(s+" bean properties:"+bd.getPropertyValues().toString());
}
}
}
在beans.xml中:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.User">
<property name="name" value="hello world"></property>
</bean>
<bean id="postProcessor" class="com.BeanFactoryProcessorTest"/>
</beans>
输出结果:
那么要知道什么时候调用BeanFactoryPostProcessor的postProcessBeanFactory方法,就需要源码分析了:
查看AbstractApplicationContext类的refresh方法:
//调用BeanFactoryPostProcessor的postProcessBeanFactory方法在这个方法的invokeBeanFactoryPostProcessors中
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
//obtainFreshBeanFactory()启动子类的refreshBeanFactory(),首先清除原有的IOC容器,然后创建DefaultListableBeanFactory容器,并进行Bean的定位、载入和解析。
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
//当前方法为空,由子类去实现。
this.postProcessBeanFactory(beanFactory);
//这里!!调用这里方法时BeanDefinition已经注册了。
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//初始化剩余的非懒加载的单例对象
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//这里
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
//PostProcessorRegistrationDelegate类的invokeBeanFactoryPostProcessors
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
//其他代码已省略,省略的代码都是初始化比BeanFactoryPostProcessor优先级高的类
//把所有工厂中存在的实现BeanFactoryPostProcessor类的所有名称拿出来。
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
//nonOrderedPostProcessorNames这个才是我们关心的
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) { //不用关心这个
// skip - already processed in first phase above
//已经存在了,不再处理。
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else { //这个才是我们关心的PostProcessor
nonOrderedPostProcessorNames.add(ppName);
}
}
// .......
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
//getBean获取自定义的BeanFactoryPostProcessor(也就是我们的BeanFactoryProcessorTest),然后添加到集合里。
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
//然后看这个方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
beanFactory.clearMetadataCache();
}
private static void invokeBeanFactoryPostProcessors(
Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
//遍历我们定义的所有BeanFactoryPostProcessor,然后执行postProcessBeanFactory。
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
postProcessor.postProcessBeanFactory(beanFactory);
}
}
2.2 BeanPostProcessor
实例化BeanPostProcessor实现类是在调用BeanFactoryPostProcessor的postProcessBeanFactory方法之后开始。不过BeanPostProcessor的postProcessBeforeInitialization方法和postProcessAfterInitialization方法都是在Bean对象初始化后(这个初始化是Bean对象的依赖注入已经完成了)。postProcessBeforeInitialization方法是在init方法之前,postProcessAfterInitialization方法是在init方法之后(这个init方法是我们在XML定义的属性:init-method)。
每个BeanDefinition的实例化(之前没被实例化过)都会经过AbstractBeanFactory类的getBean这个方法,然后getBean方法中调用doGetBean方法,然后doGetBean方法中调用getSinleton方法里的ObjectFactory类的getObject方法里的creatBean方法,然后creatBean方法中调用initializeBean方法,在initializeBean方法中:postProcessBeforeInitialization方法先执行,然后是init方法,之后是postProcessAfterInitialization方法。
脑图:
待补充