一.先看总体流程图
二.根据程序加载的流程剖析spring源代码,首先准备我们的测试入库及xml文件
(1)xml,定义了一个id为person的bean,给person的两个属性name、age分别附上值
<?xml version="1.0" encoding="UTF-8"?>
<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 class="MyBeanFactoryPostProcesser"></bean>-->
<bean class="Person" id="person">
<property name="name" value="johnny"/>
<property name="age" value="10"/>
</bean>
</beans>
(2)person实体,两个字段name、age
public class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
(3)测试主程序入口,加载xml,进行debug调试
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo1 {
public static void main(String[] args) throws Exception{
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("demo.xml");
Person person = classPathXmlApplicationContext.getBean(Person.class);
System.out.println(person);
}
}
三.debug依据源代码进行方法剖析,主要对重要方法进行解析
1.设置运行环境
(1)super(parent):主要方法:
Environment parentEnvironment = parent.getEnvironment()设置运行环境
(2)setConfigLocations(configLocations)把传递进来的demo.xml赋值非全局变量configLocations
2.核心处理方法入口为refresh(),先看第一个主要方法prepareRefresh(),spring5.3之后加了程序的执行步骤方法
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
prepareRefresh(): * 做容器刷新前的准备
* 1.设置容器的启动时间
* 2.设置活跃状态为true
* 3.设置关闭状态为false
* 4.获取Environment对象,并加载当前系统的环境到Environment中
* 5.准备监听器和事件的集合对象,默认为空
this.startupDate = System.currentTimeMillis();//获取到系统时间
this.closed.set(false);//关闭程序设置为false
this.active.set(true); //运行标识设置为true
//初始化属性资源
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
//创建并获取环境对象,验证需要的属性文件是否已经加入环境中
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
//判断刷新前的运用程序监听集合是否为空,为空则将监听器添加到此集合中,集合方式为LinkedHashSet
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
//不为空,则清空监听器
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
//创建刷新前的事件集合
this.earlyApplicationEvents = new LinkedHashSet<>();
3.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory():校验是否存在BeanFactory工厂,存在则销毁,不存在则创建,最重要的就是BeanDefinition,初始化documentReader并进行Xml文件读取及解析,默认命名空间的解析,自定义标签的解析,不替代${特殊字符。解析xml文件过程:
创建beanFactory->创建XmlBeanDefinitionReader->根据加载的xml配置使用ResourceLoader获取Resource[]->遍历Resource[]获取InputStream 文件输入流->通过InputStream 获取Document 对象->通过BeanDefinitionDocumentReader对Document进行解析①先来看第一个方法refreshBeanFactory()
if (hasBeanFactory()) { //校验是否存在BeanFactory工厂
destroyBeans(); //存在则销毁Beans
closeBeanFactory(); //存在则销毁BeanFactory工厂
}
try {
//创建一个BeanFactory工厂
DefaultListableBeanFactory beanFactory = createBeanFactory();
//设置工厂序列化id,可以使用id反序列化BeanFactory
beanFactory.setSerializationId(getId());
//定制工厂,没有执行方法,设置相关属性,包括是否允许覆盖同名称的不同定义的对象已经循环依赖
customizeBeanFactory(beanFactory);
//初始化documentReader并进行Xml文件读取及解析,默认命名空间的解析,自定义标签的解析
//执行完成后BeanDefinitionMap和BeanDefinitionNames都会有值,存放解析的Xml文件值,不会替换${等读取到的符号
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
②具体来看loadBeanDefinitions(beanFactory):初始化documentReader并进行Xml文件读取及解析,默认命名空间的解析,自定义标签的解析;执行完成后BeanDefinitionMap和BeanDefinitionNames都会有值,存放解析的Xml文件值,不会替换${等读取到的符号
//创建解析Xml的读取类XmlBeanDefinitionReader,并通过回调设置到beanFacotry中
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//给reader对象设置环境对象
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));//读取xsd、dtd约束表头
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
//初始化beanDefinitionReader对象,此处设置配置文件是否需要进行验证
initBeanDefinitionReader(beanDefinitionReader);
//开始完成beandefinition的加载
loadBeanDefinitions(beanDefinitionReader);
③再来看其下的方法loadBeanDefinitions(beanDefinitionReader):开始完成beandefinition的加载
//以String的方式获取配置文件的资源位置,获取第一步设置的configLocations参数
String[] configLocations = getConfigLocations();
if (configLocations != null) {//读取到加载的xml配置地址
reader.loadBeanDefinitions(configLocations);
}
④再来看其下的reader.loadBeanDefinitions(configLocations):通过读取到的配置信息加载beanDefinitions
int count = 0;
for (String location : locations) {
count += loadBeanDefinitions(location);
}
return count;
⑤再来看其下的loadBeanDefinitions(location):根据配置的xml信息获取beanDefinitions
//此处获取ResourceLoader对象
ResourceLoader resourceLoader = getResourceLoader();
//调动DefaultResourceLoader的getResource完成具体的resource定位
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int count = loadBeanDefinitions(resources);
此时的resources截图:
⑥再来看其下的loadBeanDefinitions(resources):通过具体的文件定位获取到resource来获取beanDefinitions
int count = 0;
for (Resource resource : resources) {
count += loadBeanDefinitions(resource);
}
return count;
⑦再来看其下的loadBeanDefinitions(resource):通过某个resource获取beandefinitions,使用InputStream输入流获取xml里的配置信息
//从encodedResource中获取已经封装的resource对象,并再次从Resource中获取inputStream
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//逻辑处理的核心步骤
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
⑧再来看其下的doLoadBeanDefinitions(inputSource, encodedResource.getResource()):逻辑处理的核心步骤,开始通过获取的文件流和resource来获取Document对象,再由doc注册
try {
//此处获取xml文件的document对象,这个解析过程是由DocumentLoader完成的,
//从String[] -String -Resource[] -resource ,最终将resourc读取成document
Document doc = doLoadDocument(inputSource, resource);
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
⑨再来看其下的Document doc = doLoadDocument(inputSource, resource):此处获取xml文件的document对象,这个解析过程是由DocumentLoader完成的,
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isTraceEnabled()) {
logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]");
}
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
return builder.parse(inputSource);
⑩再来看int count = registerBeanDefinitions(doc, resource):对xml的beanDefinition进行解析,完成具体的解析过程
//对xml的beanDefinition进行解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//完成具体的解析过程
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
此时的beanFactory已经解析完xml的值,beanDefinitionMap、beanDefinitionNames已经解析到xml中定义的值,以及是否懒加载、是否有依赖的值情况:
4.prepareBeanFactory(beanFactory):设置beanFactory属性值,设置类加载器,#{表达式、添加BeanPostProcessor,忽略接口,创建单例模式,对各种属性进行填充
//设置beanFactory的classloader为当前context的classLoader
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
//设置beanFactory的语言表达式处理器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));//设置表达式处理字符,列#{ }等
}
//为beanFactory设置一个默认的editorRegistrar
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//设置beanPostProcessor,ApplicationContextAwareProcessor用来完成某些aware对象的引入
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //移出之前的,添加新的BeanPostProcessor
//对某些接口进行忽略自动装配处理,因为这些接口是由容器通过set进行值的设置,autowire方式时,忽略这些接口
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);//忽略依赖的接口
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
//设置几个自动装配的特殊规则,当在ioc初始化时,有多个实现,那么就使用指定的对象进行引入
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
//注册beanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
//增加对Aspetcj的支持,在java中植入分为三种方式:编译器植入、类加载器植入、运行期植入
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
//注册默认的系统环境到bean中
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {//environment的bean
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());//环境注册为单例
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {//systemProperties
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {//systemEnvironment
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {//applicationStartup
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
执行完成后beanFactory新赋值情况
5.postProcessBeanFactory(beanFactory):子类覆盖方法做而外的处理,此处一般我们不做任何的扩展工作,但是可以查看web中的代码,是有具体实现的。自定义的子类实现BeanFactoryPostProcesser,需要重写postProcessBeanFactory方法,实现扩展
public class MyBeanFactoryPostProcesser implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("自定义的扩展方法========");
}
}
xml中添加bean
<bean class="MyBeanFactoryPostProcesser"></bean>
程序启动后调用重写的postProcessBeanFactory方法
6.invokeBeanFactoryPostProcessors(beanFactory):调用各种Beanfactory处理器,实例化并调用所有已注册的BeanFactoryPostProcessor,替代解析到的数据库连接${},在执行此方法之前,spring5.3之后加了执行步骤的记录;①看invokeBeanFactoryPostProcessors(beanFactory)方法
//记录执行步骤,spring5.3之后才添加,分步记录有关特定阶段或操作期间发生的操作的指标
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
//实例化并调用所有已注册的BeanFactoryPostProcessor
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
②再来看其下的PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());实例化并调用所有已注册的BeanFactoryPostProcessor
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<String>();
// 1.判断beanFactory是否为BeanDefinitionRegistry,beanFactory为DefaultListableBeanFactory,
// 而DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,因此这边为true
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 用于存放普通的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
// 用于存放BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
// 2.首先处理入参中的beanFactoryPostProcessors
// 遍历所有的beanFactoryPostProcessors, 将BeanDefinitionRegistryPostProcessor和普通BeanFactoryPostProcessor区分开
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 2.1 如果是BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 2.1.1 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 2.1.2 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors.add(registryProcessor);
} else {
// 2.2 否则,只是普通的BeanFactoryPostProcessor
// 2.2.1 添加到regularPostProcessors(用于最后执行postProcessBeanFactory方法)
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 用于保存本次要执行的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
// 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 3.2 遍历postProcessorNames
for (String ppName : postProcessorNames) {
// 3.3 校验是否实现了PriorityOrdered接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 3.4 获取ppName对应的bean实例, 添加到currentRegistryProcessors中,
// beanFactory.getBean: 这边getBean方法会触发创建ppName对应的bean对象, 目前暂不深入解析
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 3.5 将要被执行的加入processedBeans,避免后续重复执行
processedBeans.add(ppName);
}
}
// 3.6 进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序)
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 3.7 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors.addAll(currentRegistryProcessors);
// 3.8 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 3.9 执行完毕后, 清空currentRegistryProcessors
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 4.调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类(过程跟上面的步骤3基本一样)
// 4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor,
// 可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 校验是否实现了Ordered接口,并且还未执行过
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 4.2 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 5.最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors
boolean reiterate = true;
while (reiterate) {
reiterate = false;
// 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 5.2 跳过已经执行过的
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
// 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor,
// 因此这边将reiterate赋值为true, 代表需要再循环查找一次
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 6.调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 7.最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor已经全部处理完毕,
// 下面开始处理容器中的所有BeanFactoryPostProcessor
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 8.找出所有实现BeanFactoryPostProcessor接口的类
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 用于存放实现了PriorityOrdered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
// 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
List<String> orderedPostProcessorNames = new ArrayList<String>();
// 用于存放普通BeanFactoryPostProcessor的beanName
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
// 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开
for (String ppName : postProcessorNames) {
// 8.2 跳过已经执行过的
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 8.3 添加实现了PriorityOrdered接口的BeanFactoryPostProcessor
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 8.4 添加实现了Ordered接口的BeanFactoryPostProcessor的beanName
orderedPostProcessorNames.add(ppName);
} else {
// 8.5 添加剩下的普通BeanFactoryPostProcessor的beanName
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 9.调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor
// 9.1 对priorityOrderedPostProcessors排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 9.2 遍历priorityOrderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 10.调用所有实现Ordered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
// 10.1 获取postProcessorName对应的bean实例, 添加到orderedPostProcessors, 准备执行
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// 10.2 对orderedPostProcessors排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 10.3 遍历orderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
// 11.调用所有剩下的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
// 11.1 获取postProcessorName对应的bean实例, 添加到nonOrderedPostProcessors, 准备执行
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
// 11.2 遍历nonOrderedPostProcessors, 执行postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 12.清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),
// 因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符...
beanFactory.clearMetadataCache();
}
7.registerBeanPostProcessors(beanFactory):注册BeanPostProcessor处理器到BeanFatory,这里只是注册功能,真正调用的是getBean方法
// 从所有 Bean 定义中提取出 BeanPostProcessor 类型的 Bean,注意和 getBeanPostProcessors 的结果区分开来,虽然都是 BeanPostProcessor
// 最初的 6 个 bean,有 2 个是 BeanPostProcessor:
// AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 先按优先级,归类 BeanPostProcessor
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
if (beanFactory instanceof AbstractBeanFactory) {
// Bulk addition is more efficient against our CopyOnWriteArrayList there
((AbstractBeanFactory) beanFactory).addBeanPostProcessors(postProcessors);
}
else {
// 把类型是 BeanPostProcessor 的 Bean,注册到 beanFactory 里去
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
- 按照
PriorityOrdered
、Ordered
、其他的顺序注册所有的BeanPostProcessor
- 重新注册所有的内部处理器
internalPostProcessors
(实现了MergedBeanDefinitionPostProcessor
)。重新注册会先移除原来注册的,重新进行注册,就会排在后面; - 最后,重新注册
ApplicationListenerDetector
。将其注册在处理器链的最后。此时beanPostProcessor值
8.initMessageSource():为上下文初始化message语言,即不同的消息体,国际化处理
//判断beanFactory中是否有名字为messageSource的bean,
// 如果有,从beanFactory中获取并且判断获取的是不是HierarchicalMessageSource类型的,如果是设置其父级消息源
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {//messageSource
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
9.initApplicationEventMulticaster():根据beanfactory创建事件监听多路广播器,设置成单例广播器;先判断有没有自定义的ApplicationEventMulticaster,没有的话就注册一个。SimpleApplicationEventMulticaster就是用来发布事件用的
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
/**
* 判断容器中是否存在bdName为applicationEventMulticaster的bd
* 也就是自定义的事件监听多路广播器,必须实现ApplicationEventMulticaster接口
*/
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {//applicationEventMulticaster
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
/**
* 如果没有,则默认采用SimpleApplicationEventMulticaster
*/
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);//根据beanfactory创建事件播放器
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);//applicationEventMulticaster
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
10.onRefresh():可扩展的空方法,给子类初始化其它的bean
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
11.registerListeners():通过addApplicationListener(listen)注册监听器
/**
* getApplicationListeners就是获取applicationListeners
* 是通过applicationListeners(listener)添加的
* 放入applicationListeners中
*/
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
/**
* 从容器中获取所有实现了ApplicationListener接口的bd的bdName
* 放入applicationListenerBeans
*/
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
/**
* 这里先发布早期的监听器,默认为空
*/
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
12.finishBeanFactoryInitialization(beanFactory):初始化剩下的单实例(非懒加载的);创建bean过程:
finishBeanFactoryInitialization入口-》preInstantiateSingletons()-》getBean(beanName)-》doGetBean(name, null, null, false)-》getSingleton(beanName,lambad)->调用lamabd表达式中的方法createBean(beanName, mbd, args)-> doCreateBean(beanName, mbdToUse, args)-》createBeanInstance(beanName, mbd, args)-》instantiateBean(beanName, mbd)完成对bean的实例化,属性值为空
-》populateBean(beanName, mbd, instanceWrapper)对初始化好的bean进行属性填充
->initializeBean(beanName, exposedObject, mbd)执行初始化逻辑
①先来看finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)方法:
//为上下文初始化类型转换器
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {//conversionService
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
//如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器,主要用于注解值的解析
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
//尽早初始化LoadTimeWeaverAware bean,以便尽早注册转换器
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
//禁止使用临时类加载器进行类型匹配
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
//冻结所有的bean定义,说明注册的bean将不被修改或者进一步的处理
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化剩下的单例对象
beanFactory.preInstantiateSingletons();
②再来看其下的beanFactory.preInstantiateSingletons():实例化剩下的单例对象,将所有的beandefinitionNames属性里面的名字做为数组创建对象
//将所有的beandefinitionNames属性里面的名字做为数组创建对象
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
遍历集合,触发所有非延时加载的单例bean的初始化,延时加载的单例不在此处处理;判断是否是FactoryBean,FactoryBean通过"&" + beanName获取到该bd本身
for (String beanName : beanNames) {
//合并父类BeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//条件判断:抽象 单例 非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判断是否实现了FactoryBean接口
if (isFactoryBean(beanName)) {
//根据&+beanName来获取具体的bean对象
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
//进行类型转化
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
//判断这个FactoryBean是否希望立即初始化
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
//如果希望急切的初始化,则通过beanName获取bean
if (isEagerInit) {
getBean(beanName);
}
}
}
else {//如果beanName对应Bean不是FactoryBean,只是普通的Bean,则通过beanName获取Bean
getBean(beanName);
}
}
}
③再来看其下的getBean(beanName)方法
如果beanName对应Bean不是FactoryBean,只是普通的Bean,则通过beanName获取Bean
@Override
public Object getBean(String name) throws BeansException {
//此方法是实际获取Bean的方法,也是触发依赖注入的方法
return doGetBean(name, null, null, false);
}
④再来看 doGetBean(name, null, null, false)方法:提取对应的beanName,转化的原因是,在实现FactoryBean接口之后,会变成&+beanName
String beanName = transformedBeanName(name);
BeanFactoryUtils.transformedBeanName(name)
提前检查单例对象缓存中是否有手动注册的单例对象,跟循环依赖有关联
Object sharedInstance = getSingleton(beanName)
从单例对象缓存中获取beanName对应的单例对象,先从一级缓存singletonObjects中取,没有取到值,且当前对象正处于创建中,才进if语句中,否则直接返回从缓存中取不到值;当一级缓存中取不到值而bean又处于创建中时,从二级缓存中取,二级缓存中也取不到值,并且允许创建早期对象,则一级缓存上锁,从三级缓存中取对象。一级缓存存放的是实例化和初始化后的成品对象,二级缓存存放的是实例化为初始化的半成品对象,三级缓存存放的是bean的lamba表达式。把从三级缓存取到的对象赋值给二级缓存。程序第一次执行的时候缓存是取不到任何值的
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
//从单例对象缓存中获取beanName对应的单例对象
Object singletonObject = this.singletonObjects.get(beanName);
//如果单例对象缓存中没有,并且该beanName对应的单例对象正在创建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//从早期单例缓存对象中获取单例对象,(之所以称之为早期对象,是因为earlySingletonObjects里的对象
//都是通过提前曝光的ObjectFactory创建出来的,还未进行属性填充等操作)
singletonObject = this.earlySingletonObjects.get(beanName);
//如果在早期单例对象缓存中也没有,并且允许创建早期单例对象引用
if (singletonObject == null && allowEarlyReference) {
//如果为空,则锁定全局变量,进行处理
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
//当某些方法需要提前初始化的时候,则会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletonFactoryies
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
如果if (sharedInstance != null && args == null) 不满足条件,走的程序为
//当对象都是单例的时候,会尝试解决循环依赖的问题,但是原型模式下如果存在循环依赖的问题,直接抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//如果bean定义不存在,则检查父工厂是否有
BeanFactory parentBeanFactory = getParentBeanFactory();
//如果BeanDefinitionMap中也就是已经加装的类中不包含beanName,则会从父容器中获取
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
//获取name对应的规范名称,若是前面有&,会获取到&+规范名称
String nameToLookup = originalBeanName(name);
//如果parentBeanFactory是AbstractBeanFactory的实例
if (parentBeanFactory instanceof AbstractBeanFactory) {
//调用parentBeanFactory的doGetBean方法
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
//如果有创建bean时需要使用的参数,则使用父工厂获取该bean对象,通过Bean的全类名和参数创建bean对象
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
//没有创建bean需要的参数,委托给标准的getBean方法
//使用父工厂创建bean对象,通过bean的全类名和类型创建bean对象
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
//使用父工厂创建bean对象,通过bean的全类名
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
//如果不是做类型检查,那么标识要创建bean,此处在集合中做一个记录
if (!typeCheckOnly) {
//为beanName标记为已经创建
markBeanAsCreated(beanName);
}
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
//此处做了BeanDefinition对象的转化,当从xml文件加载BeanDefinition对象的时候,封装的对象是GenericBeanDefinition
//此处要做相关转化,若是子类bean的话,需要合并父类的相关属性
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检查mbd的合法性,不合格会引发验证异常
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//若果存在依赖的bean的话,优先实例化依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
//存在依赖,需要递归依赖的bean
for (String dep : dependsOn) {
//如果beanName已注册依赖于dependentBeanName的关系,抛出异常
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册各个bean的依赖关系,方便进行销毁
registerDependentBean(dep, beanName);
try {
//递归优先实例化被依赖的bean
getBean(dep);
}
//捕捉找不到beandefinition异常,beanName依赖于缺少的bean 'dep'
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//创建bean的实例对象
if (mbd.isSingleton()) {
//返回以beanName的(原始)单例对象,如果尚未注册,则使用singletonFactory进行创建注册
sharedInstance = getSingleton(beanName, () -> {
try {
//为给定的合并后的BeanDefinition(和参数)创建一个bean对象
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
}
markBeanAsCreated(beanName):为beanName标记为已经创建
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
若果存在依赖的bean的话,优先实例化依赖的bean:
//若果存在依赖的bean的话,优先实例化依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
//存在依赖,需要递归依赖的bean
for (String dep : dependsOn) {
//如果beanName已注册依赖于dependentBeanName的关系,抛出异常
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册各个bean的依赖关系,方便进行销毁
registerDependentBean(dep, beanName);
try {
//递归优先实例化被依赖的bean
getBean(dep);
}
//捕捉找不到beandefinition异常,beanName依赖于缺少的bean 'dep'
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
⑤
getSingleton(beanName, () -> {
try {
//为给定的合并后的BeanDefinition(和参数)创建一个bean对象
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});创建bean的实例对象getSingleton()方法:传递beanNamehe和lambda表达式,从单例对象一级缓存Map中获取beanName对应的bean对象,创建单例之前的回调,默认实现将单例注册为正在创建
//使用单例对象的高速缓存map作为锁,保证线程同步
synchronized (this.singletonObjects) {
//从单例对象的高速缓存Map中获取beanName对应的bean对象
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
//如果在destructSingleton中
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
//如果当前日志级别是调试
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//创建单例之前的回调,默认实现将单例注册为正在创建
beforeSingletonCreation(beanName);
//表示生成了新的单例对象的标记,为false,标识没有生成单例对象
boolean newSingleton = false;
//有抑制异常标识,没有为true,有为false
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
//如果没有抑制异常记录
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//从单例工厂中获取对象
singletonObject = singletonFactory.getObject();
//生成了新的单例对象的标识
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
方法singletonObject = singletonFactory.getObject()调用的方法跳转到lambda表达式的return createBean(beanName, mbd, args)
⑥再来看createBean(beanName, mbd, args)方法:为给定的合并后的BeanDefinition(和参数)创建一个bean对象;锁定class,根据设置的class属性或者根据className来解析class
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
//锁定class,根据设置的class属性或者根据className来解析class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
//进行条件筛选,重新赋值RootBeanDefinition,并设置BeanClass属性
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
//重新创建RootBeanDefinition对象
mbdToUse = new RootBeanDefinition(mbd);
//设置beanClass属性值
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
//验证及准备要覆盖的方法lookup-method
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//实际创建bean的方法
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
⑦Object beanInstance = doCreateBean(beanName, mbdToUse, args):实际创建bean的方法
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//这个beanWrapper是用来持有创建出来的bean的
BeanWrapper instanceWrapper = null;
//获取factoryBean的实例化缓存
if (mbd.isSingleton()) {
//如果是单例对象,从factorybean实例缓存中移出当前bean的定义信息
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//没有就创建
if (instanceWrapper == null) {
//根据执行bean使用对象的策略创建对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//从包装类中获取原始bean,只是完成了实例化操作,字段值都是空
Object bean = instanceWrapper.getWrappedInstance();
//获取bean对象的class属性
Class<?> beanType = instanceWrapper.getWrappedClass();
//如果不等于NullBean类型,则修改目标类型
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
//允许beanPostprocesser去修改合并后的beandefinition
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//判断当前bean是否需要提前曝光,单例&允许循环依赖&当前bean正在创建中,检查循环依赖
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//为了避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
//初始化bean实例
Object exposedObject = bean;
try {
//对bean进行属性填充,将各个属性值注入,其中,可能存在依赖其他bean的属性,则会递归初始化依赖的bean
populateBean(beanName, mbd, instanceWrapper);
//执行初始化逻辑
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
//从缓存中获取具体对象
Object earlySingletonReference = getSingleton(beanName, false);
//earlySingletonReference只有在检测到有循环依赖的情况才不为空
if (earlySingletonReference != null) {
//如果exposedObject没有在初始化中被改变,也就是没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
//注册bean对象,方便在后续容器销毁时销毁对象
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
⑧instanceWrapper = createBeanInstance(beanName, mbd, args):根据执行bean使用对象的策略创建对象
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
//确认需要创建的bean实例可以被实例化
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//确保class不为空,并且访问权限是public
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
//判断当前beandefinition是否包含实例供应器,此处相当于一个回调方法,通过回调方法来创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//如果工厂方法不为空,则使用工厂方法初始化策略
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
//一个类可能有多个构造器,所以Spring得根据参数个数,参数类型确认调用的构造器
//在使用构造器创建实例后,Spring会将解析过后确定下来的构造器或工厂方法放到缓存中,避免再次创建相同bean时再解析
// Shortcut when re-creating the same bean...
//标记下,防止创建同一个bean
boolean resolved = false;
//是否需要自动装配
boolean autowireNecessary = false;
//如果没有参数
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
//因为一个类可能有多个构造器,所以需要根据参数类型确认调用的构造器
//因为判断过程会比较,所以spring会将解析、确定好的构造函数缓存到RootBeanDefinition的resolvedConstructorOrFactoryMethod中
//在下次创建相同的bean是,直接从RootBeanDefiniton中的属性resolvedConstructorOrFactoryMethod缓存只获取,避免重复解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//有构造函数或者工厂方法
if (resolved) {
//构造器有参数
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {//使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
//从bean后置处理中为自动装配寻找构造方法,有且仅有一个有参构造方法或者有且仅有@Autowired注解构造
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
/**
* 以下情况符合其一即可进入
* 1.存在可选构造方法、
* 2.自动装配模型为构造函数自动装配
* 3.给BeanDefinition设置参数构造值
* 4.有参与构造函数列表的参数
*/
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
//找出最合适的构造方法
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
//构造函数自动注入
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
//使用无参构造函数创建对象,
return instantiateBean(beanName, mbd);
}
⑨instantiateBean(beanName, mbd):使用无参构造函数创建对象
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
//获取实例化策略,并且进行实例化
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
//包装成BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
至此BeanWrapper实例化完成,字段值都是空
判断当前bean是否需要提前曝光,单例&允许循环依赖&当前bean正在创建中,检查循环依赖,关于循环依赖的问题,在下一篇文章中体现。为了避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂,把bean和singletonFactories放到三级缓存中
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
//使用singletonObjects加锁,保证线程安全
synchronized (this.singletonObjects) {
//如果单例对象的高速缓存【bean名称-bean实例】没有beanname的对象
if (!this.singletonObjects.containsKey(beanName)) {
//将beanName,singletonFactory放到单例工厂高速缓存【beanName-singletonFatory】
this.singletonFactories.put(beanName, singletonFactory);
//从早前单例对象的高速缓存【beanname,bean实例】,移出beaName的相关缓存对象
this.earlySingletonObjects.remove(beanName);
//将beanName添加已注册的单例集中
this.registeredSingletons.add(beanName);
}
}
}
⑩populateBean(beanName, mbd, instanceWrapper):对初始化好的bean进行属性填充,将各个属性值注入,其中,可能存在依赖其他bean的属性,则会递归初始化依赖的bean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//如果beanWrapper为空
if (bw == null) {
//如果mbd有需要设置的属性
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
//没有可填充的属性,直接调过
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
//给任何实现了InstantiationAwareBeanPostPorcessors的子类机会去修改bean的状态再设置属性之前,可以被用来支持类型的字段注入
//否是“synthetic",一般是指只有Aop相关的pointCut配置或者Advice配置才会将synthetic设置为true
//如果mdb是不是syntheic且工厂拥有InstantiationAwareBeanPostProceessor
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
//遍历工厂中的beanPostProcessor对象
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
//若果bp是InstantiationAwareBeanPostProcessor实例
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
//propertyValues包含一个或多个PropertyValue对象的容器,通常包括针对特定目标Bean的一次更新
//如果mdb有propertyVlaues就获取其propertyvalues
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//获取mbd的自动装配模式
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
//如果装配模式为按名称自动装配模式,或者按类型自动装配bean模式
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//MutablePropertyValues:PropertyValues接口的默认实现,允许对属性进行简单操作,并提供构造函数来支持从映射进行深度复制和构造
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
//根据autowire名称添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
//通过bw的propertyDescriptor属性名,查找出对应的bean对象,将其添加到newPvs中
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
//根据自动装配的类型来添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//通过bw的propertyDescriptor属性名,查找出对应的bean对象,将其添加到newPvs中
autowireByType(beanName, mbd, bw, newPvs);
}
//让pvs重新应用newPvs,newPvs已经包含了pvs的属性值,以及通过名称、类型自动装配所得到的属性值
pvs = newPvs;
}
//工厂是否拥有了InstantiationAwareBeanPostProcessors
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//mbd.getDependencyCheck()默认返回DEPENDENCY_CHECK_NONE,默认不检查
//是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
//进过筛选的PropertyDescriptor数组,
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
//运用给定的属性值,解决任何运用在这个bean工厂运行时其它bean的引用,必须使用深拷贝,所以我们不会永久的修改这个属性
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
属性填充完后的情况
⑪exposedObject = initializeBean(beanName, exposedObject, mbd):执行初始化逻辑,synthetic:一般是只有aop相关的pointerCut配置或者advice才会将synthetic设置为true
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
//如果安全管理器不为空
if (System.getSecurityManager() != null) {
//以特权的方式执行回调bean中的aware接口方法
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//Aware接口处理器,只设置这三个接口BeanNameAware、BeanClassLoaderAware、BeanFactoryAware,设置了beanfactory属性值
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
//如果mbd不为空 || mbd不是synthetic,一般是只有aop相关的pointerCut配置或者advice才会将synthetic设置为true
if (mbd == null || !mbd.isSynthetic()) {
//将beanpostprocesser运用到给定的现有bean,调用他们的postProcesserBeforeInitialization
//返回的bean实例可能是原始bean包装器,此处给bean的applicationContext属性赋上值
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//调用初始化方法,先调用bean的initializingBean接口方法,后调用bean的自定义初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
//捕获调用初始化是的异常方法,重新抛出bean创建异常,调用初始化方法失败
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
//如果mbd==null || mbd不是Synthetic
if (mbd == null || !mbd.isSynthetic()) {
//将BeanPostProcesser运用到给定的bean中
//返回的bean可能是原始Bean包装器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
//返回包装后的bean
return wrappedBean;
}
invokeAwareMethods(beanName, bean):Aware接口处理器,只设置这三个接口BeanNameAware、BeanClassLoaderAware、BeanFactoryAware,设置了beanfactory属性值
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
此时返回到底⑤步中的传递lamabda标识式,参数sharedInstance为当前创建的bean
⑫Object singletonInstance = getSingleton(beanName):获取缓存中的bean,主要体现在循环依赖上
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
//从单例对象缓存中获取beanName对应的单例对象
Object singletonObject = this.singletonObjects.get(beanName);
//如果单例对象缓存中没有,并且该beanName对应的单例对象正在创建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//从早期单例缓存对象中获取单例对象,(之所以称之为早期对象,是因为earlySingletonObjects里的对象
//都是通过提前曝光的ObjectFactory创建出来的,还未进行属性填充等操作)
singletonObject = this.earlySingletonObjects.get(beanName);
//如果在早期单例对象缓存中也没有,并且允许创建早期单例对象引用
if (singletonObject == null && allowEarlyReference) {
//如果为空,则锁定全局变量,进行处理
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
//当某些方法需要提前初始化的时候,则会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletonFactoryies
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
至此实例化初始化完bean,beanFactory截图
13.finishRefresh():清除上下文级别的资源缓存、为此上下文初始化生命周期处理器、首先将刷新传播到生命周期处理器
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
//清除上下文级别的资源缓存(例如来自扫描的ASM元数据)
clearResourceCaches();
// Initialize lifecycle processor for this context.
//为此上下文初始化生命周期处理器
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
//首先将刷新传播到生命周期处理器
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
if (!NativeDetector.inNativeImage()) {
LiveBeansView.registerApplicationContext(this);
}
}
①首先来看initLifecycleProcessor():为此上下文初始化生命周期处理器
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 1.判断BeanFactory是否已经存在生命周期处理器(固定使用beanName=lifecycleProcessor)
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {//lifecycleProcessor
// 1.1 如果已经存在,则将该bean赋值给lifecycleProcessor
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
// 1.2 如果不存在,则使用DefaultLifecycleProcesso
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
// 并将DefaultLifecycleProcessor作为默认的生命周期处理器,注册到BeanFactory中
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);//lifecycleProcessor
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
添加完后的registerSingleton截图