1

源码学习-Spring 源码分析

 2 years ago
source link: https://mikeygithub.github.io/2022/02/28/yuque/gx3k97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
源码学习-Spring 源码分析

源码学_

Mikey 2022年2月28日 下午

10.3k 字

164 分钟

5 次

spring 是一款轻量级的框架,主要包含的功能有 AOP、IOC(DI),包含的模块如下

spring
├── aopalliance-1.0.jar
├── commons-logging-1.2.jar
├── spring-aop-5.2.3.RELEASE.jar
├── spring-aspects-5.2.3.RELEASE.jar
├── spring-beans-5.2.3.RELEASE.jar
├── spring-context-5.2.3.RELEASE.jar
├── spring-context-support-5.2.3.RELEASE.jar
├── spring-core-5.2.3.RELEASE.jar
├── spring-expression-5.2.3.RELEASE.jar
├── spring-instrument-5.2.3.RELEASE.jar
├── spring-jdbc-5.2.3.RELEASE.jar
├── spring-jms-5.2.3.RELEASE.jar
├── spring-messaging-5.2.3.RELEASE.jar
├── spring-orm-5.2.3.RELEASE.jar
├── spring-oxm-5.2.3.RELEASE.jar
├── spring-test-5.2.3.RELEASE.jar
└── spring-tx-5.2.3.RELEASE.jar

1.加载流程分析

1.1 新建立 maven 项目

<?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">
<beans>
<bean id="messageService" class="com.analyxe.service.impl.MessageServiceImpl"/>
</beans>
</beans>
public interface MessageService {
public String getMessage();
}
public class MessageServiceImpl implements MessageService {
@Override
public String getMessage() {
System.out.println("get message ......");
return "MESSAGE";
}
}
public class Main {
public static void main(String[] args) {
//上下文
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//获取bean
MessageService messageService = (MessageService) context.getBean("messageService");
//bean调用
String message = messageService.getMessage();
System.out.println(message);
}
}

1.2 代码跟踪

下面我们一步一步来代码跟踪

1.2.1 调用应用上下文构造方法

//因为我们使用的是xml方式加载bean
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
//调用构造器初始化
this(new String[]{configLocation}, true, (ApplicationContext)null);
}

1.2.2 构造方法

//构造方法
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
super(parent);//1.调用父类AbstractXmlApplicationContext(看上图)构造方法
this.setConfigLocations(configLocations);//2.设置配置文件位置
if (refresh) {//是否刷新容器,默认传进来为true
this.refresh();//3.刷新容器(核心方法这个很重要下面会详细讲)
}
}

3.再看看其调用 ClassPathXmlApplicationContext 父类构造方法具体是什么

public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
super(parent);//调用父类AbstractRefreshableConfigApplicationContext(看上图)构造方法
}

4.再看看其调用 AbstractXmlApplicationContext 父类构造方法具体是什么,它又调用父类

public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) {
super(parent);//调用父类AbstractApplicationContext(看上图)构造方法
}

5.我们瞧瞧这个 AbstractApplicationContext 的构造方法

public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();//构造方法设置资源模式解析器
this.setParent(parent);//设置ApplicationContext(顶层接口)
}
//设置资源模式解析器
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
//返回设置资源模式解析器PathMatchingResourcePatternResolver
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}

6.设置 AbstractApplicationContext 环境配置信息

public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;//设置ApplicationContext
if (parent != null) {//如果父级ApplicationContext为空则
Environment parentEnvironment = parent.getEnvironment();//获取父级环境
if (parentEnvironment instanceof ConfigurableEnvironment) {//如果父级环境是ConfigurableEnvironment类型
this.getEnvironment().merge((ConfigurableEnvironment)parentEnvironment);//合并配置信息到子类环境
}
}
}

1.2.7 设置加载配置文件

处理加载配置文件路径,见 1.2.2 中的 2

public void setConfigLocations(@Nullable String... locations) {//可配置多个路径
if (locations != null) {//如果不为空则进行加载
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();//
}
} else {
this.configLocations = null;
}
}
//处理路径
protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);//主要是对输入的路径进行验证和替换${}占位符等
}
//获取配置的环境信息
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {//如果没有进行配置则默认创建一个StandardEnvironment
this.environment = createEnvironment();
}
return this.environment;
}
//默认创建一个StandardEnvironment
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}

1.2.8 刷新容器(核心)

判断是否需要刷新容器,见 1.2.2 中的 3

public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {//加锁包装单一线程执行
// 1.准备刷新容器
prepareRefresh();
// 2.告诉子类刷新内部beanFactory(创建beanfactory)
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3.准备beanFactory以便在容器中使用。
prepareBeanFactory(beanFactory);
try {
// 4.Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// 5.Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// 6.Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// 7.Initialize message source for this context.
initMessageSource();
// 8.Initialize event multicaster for this context.
initApplicationEventMulticaster();
// 9.初始化特定容器子类中的其他特殊bean.
onRefresh();
// 10.检查监听器并注册
registerListeners();
// 11.实例化所有的 singletons bean (除了lazy-init外).
finishBeanFactoryInitialization(beanFactory);
// 12.最后容器构造完成发布其事件
finishRefresh();
}catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}

1.2.8.1 prepareRefresh (预刷新处理)

protected void prepareRefresh() {
// 切换到激活状态
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
} else {
logger.debug("Refreshing " + getDisplayName());
}
}
// 在上下文环境中初始化任何占位符属性源。(默认不做操作,只有在web环境下更新环境)
initPropertySources();
//验证所有标记为需要的属性是否可解决
getEnvironment().validateRequiredProperties();
// 存储预刷新应用程序侦听器
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
} else {
// 将本地应用程序侦听器重置为预刷新状态
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
//允许收集早期应用程序事件,将在multicaster可用后发布
this.earlyApplicationEvents = new LinkedHashSet<>();
}

1.2.8.2 obtainFreshBeanFactory (获取最新 BeanFactory)

1.刷新 bean 工厂 2.返回 bean 工厂

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();//1.刷新bean工厂
return getBeanFactory();//2.返回bean工厂
}
//1.刷新bean工厂
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {//如果已经存在bean工厂则进行关闭
destroyBeans();//销毁beans
closeBeanFactory();//关闭bean工厂
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();//创建bean工厂
beanFactory.setSerializationId(getId());//设置beanFactory序列化id
customizeBeanFactory(beanFactory);//自定义bean工厂
loadBeanDefinitions(beanFactory);//加载bean定义
this.beanFactory = beanFactory;//设置最新bean工厂到当前上下文
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
//2.返回bean工厂
public final ConfigurableListableBeanFactory getBeanFactory() {
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext");
}
return beanFactory;
}

1.刷新 bean 工厂

protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {//如果已经存在bean工厂则进行关闭
destroyBeans();//销毁beans
closeBeanFactory();//关闭bean工厂
}
try {
//为此上下文创建一个内部bean工厂。
//为每次refresh尝试调用。
//<默认实现会创建一个org.springframework.beans.factory.support.DefaultListableBeanFactory
//使用getInternalParentBeanFactory
//上下文的父对象作为父bean工厂。可以在子类中重写,
//例如,自定义DefaultListableBeanFactory的设置。
//返回此上下文的bean工厂
DefaultListableBeanFactory beanFactory = createBeanFactory();//创建bean工厂
beanFactory.setSerializationId(getId());//设置beanFactory序列化id
customizeBeanFactory(beanFactory);//自定义bean工厂
loadBeanDefinitions(beanFactory);//加载bean定义
this.beanFactory = beanFactory;//设置最新bean工厂到当前上下文
} catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

创建默认的 bean 工厂

protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent());
}

默认 beanFactory(DefaultListableBeanFactory)

//构造方法
public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
super(parentBeanFactory);
}

设置排查自动注入的接口和实例生成策略

public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
//构造器
public AbstractAutowireCapableBeanFactory() {
super();
//忽略自动关联的给定依赖接口。通常会被应用程序上下文用来注册通过其他方式解决的依赖关系,如BeanFactory通过BeanFactoryAware或ApplicationContext通过ApplicationContextAware。
//默认情况下,仅忽略BeanFactoryAware接口。对于要忽略的其他类型,请为每个类型调用此方法。
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
//设置实例化策略
if (NativeDetector.inNativeImage()) {
this.instantiationStrategy = new SimpleInstantiationStrategy();//简单实例化策略
} else {
this.instantiationStrategy = new CglibSubclassingInstantiationStrategy();//使用cglib子类实例化策略
}
}

设置父类 bean 工厂

public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
if (this == parentBeanFactory) {
throw new IllegalStateException("Cannot set parent bean factory to self");
}
this.parentBeanFactory = parentBeanFactory;
}

此时 beanFactory 完成初始化

1.2.8.3 customizeBeanFactory(自定义 bean 工厂)

在 Spring 中支持我们自定义 beanFactory

protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
//是否允许覆盖
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//设置允许循环引用
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}

1.2.8.4 loadBeanDefinitions(加载 bean 定义)

1.当前我们使用的是 xml 的方式在类路径下加载,所以会使用的加载器是

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 为给定BeanFactory创建新的XmlBeanDefinitionReader。
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//使用此上下文的资源加载环境
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//允许子类提供读取器的自定义初始化,然后继续加载bean定义。
initBeanDefinitionReader(beanDefinitionReader);
//加载bean定义方法(核心)
loadBeanDefinitions(beanDefinitionReader);
}

2.使用给定的 XmlBeanDefinitionReader 加载 bean 定义。bean 工厂的生命周期由 refreshBeanFactory 处理方法;因此,这个方法应该只是加载和/或注册 bean 定义

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);//通过Resource加载(本次没有配置Resource)
}
String[] configLocations = getConfigLocations();//通过配置的路径加载(我们配置的是classpath:applicationContext.xml)
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}

3.加载配置的文件

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
for (String location : locations) {
count += loadBeanDefinitions(location);//加载配置的文件
}
return count;
}
//实际调用
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}

4.根据 resourceLoader 匹配加载的路径(类路径和绝对路径)

public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {//类路径下的加载器
// 资源模式匹配可用
try {
//1.加载器的加载方法方法 AbstractApplicationContext、GenericApplicationContext、StubWebApplicationContext、
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//2.通过resources进行加载bean
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
}
return count;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("Could not resolve bean definition resource pattern [" + location + "]", ex);
}
} else {
// 绝对路径加载
Resource resource = resourceLoader.getResource(location);
int count = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
}
return count;
}
}

5.根据输入的路径进行匹配加载

public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {//"classpath*:"开头(所有类路径下)
// a class path resource (multiple resources for same name possible)
if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
// 类路径资源模式
return findPathMatchingResources(locationPattern);
} else {
// 具有给定名称的所有类路径资源
return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
}
} else {//否则是指的类路径
//通常只在这里的前缀后面寻找模式,在Tomcat上只在其“war:”协议的“*/”分隔符后面寻找模式。
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 : locationPattern.indexOf(':') + 1);
if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
// 文件格式
return findPathMatchingResources(locationPattern);
} else {
// 具有给定名称的单个资源
return new Resource[] {getResourceLoader().getResource(locationPattern)};//chi's
}
}
}

6.通过 ResourceLoader 进行 getResource 加载资源(注意这里只是根据传入的路径进行构造 ClassPathResource 对象)

public static final String CLASSPATH_URL_PREFIX = "classpath:";
public static final String FILE_URL_PREFIX = "file:";
public static final String JAR_URL_PREFIX = "jar:";
public static final String WAR_URL_PREFIX = "war:";
public static final String URL_PROTOCOL_FILE = "file";
public static final String URL_PROTOCOL_JAR = "jar";
public static final String URL_PROTOCOL_WAR = "war";
public static final String URL_PROTOCOL_ZIP = "zip";
public static final String URL_PROTOCOL_WSJAR = "wsjar";
public static final String URL_PROTOCOL_VFSZIP = "vfszip";
public static final String URL_PROTOCOL_VFSFILE = "vfsfile";
public static final String URL_PROTOCOL_VFS = "vfs";
public static final String JAR_FILE_EXTENSION = ".jar";
public static final String JAR_URL_SEPARATOR = "!/";
public static final String WAR_URL_SEPARATOR = "*/";
public Resource getResource(String location) {//classpath:applicationContext.xml
Assert.notNull(location, "Location must not be null");
//尝试遍历协议获取
for (ProtocolResolver protocolResolver : getProtocolResolvers()) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
//否则在本地查找
if (location.startsWith("/")) {//是否以/开头
return getResourceByPath(location);
} else if (location.startsWith(CLASSPATH_URL_PREFIX)) {//是否以"classpath:"开头,是则去掉classpath:直接进行加载
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
} else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
} catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}

7.构造的 ClassPathResource 对象

public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
Assert.notNull(path, "Path must not be null");
String pathToUse = StringUtils.cleanPath(path);
if (pathToUse.startsWith("/")) {//去除
pathToUse = pathToUse.substring(1);
}
this.path = pathToUse;
this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}

8.回到 4-2 中通过获取回来的 Resource 加载 bean

public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int count = 0;
for (Resource resource : resources) {
count += loadBeanDefinitions(resource);//开始加载
}
return count;
}
//我们使用的bean配置方式通过xml配置,所以会使用XmlBeanDefinitionReader来加载
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}
//通过ThreadLocal获取当前正在加载的资源
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
//把当前需要加载的Resource加入判断是否已经加载过,如果加载过抛出异常
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException("Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
//获取文件的输入流
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {//设置编码
inputSource.setEncoding(encodedResource.getEncoding());
}
//核心方法(加载bean定义)
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("IOException parsing XML document from " + encodedResource.getResource(), ex);
} finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}

9.SAX 解析 XML 文件

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
try {
//1.核心方法(SAX进行解析XML)
Document doc = doLoadDocument(inputSource, resource);
//2.核心方法(注册bean)
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
} catch (BeanDefinitionStoreException ex) {
throw ex;
} catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
} catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", ex);
} catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, ex);
} catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, ex);
} catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, ex);
}
}

10.注册 Bean

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//核心方法(注册bean)
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//注册bean定义
doRegisterBeanDefinitions(doc.getDocumentElement());
}
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
//创建一个Bean定义解析器委托
this.delegate = createDelegate(getReaderContext(), root, parent);
//确定给定节点是否指示默认名称空间
//主要判断xml文件是否符号 SPR-12458 规范
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
preProcessXml(root);//前置处理xml(在DefaultBeanDefinitionDocumentReader)默认不做什么操作
parseBeanDefinitions(root, this.delegate);//解析bean定义(核心方法)
postProcessXml(root);//后置处理xml(在DefaultBeanDefinitionDocumentReader)默认不做什么操作
this.delegate = parent;
}

11.解析 xml 配置的 bean 类型

根据 xml 配置的类型进行区分加载

//	public static final String NESTED_BEANS_ELEMENT = "beans";
// public static final String ALIAS_ELEMENT = "alias";
// public static final String NAME_ATTRIBUTE = "name";
// public static final String ALIAS_ATTRIBUTE = "alias";
// public static final String IMPORT_ELEMENT = "import";
// public static final String RESOURCE_ATTRIBUTE = "resource";
// public static final String PROFILE_ATTRIBUTE = "profile";
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);//导入类型
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);//别名类型
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
//我们设置的配置文件是bean类型所以进这个方法
processBeanDefinition(ele, delegate);//bean类型
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
doRegisterBeanDefinitions(ele);//嵌套bean类型
}
}

12.处理 bean 定义

/**
* Process the given bean element, parsing the bean definition and registering it with the registry.
*/
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//解析bean定义持有对象
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
//装饰bean定义
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
//注册最后实例
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex);
}
// 发送bean注册事件
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
// 获取beanName
String beanName = definitionHolder.getBeanName();
//
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// 获取别名,如果存在则进行注册
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}

13.这一步主要是为了将 bean 定义加入到缓存中去 beanDefinitionMap

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {

Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");

if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();//验证bean是否有覆盖方法
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Validation of bean definition failed", ex);
}
}
//尝试从beanDefinitionMap获取当前要注册的bean
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
//已经存在当前bean定义
if (existingDefinition != null) {//如果beanDefinitionMap已经存在该bean定义判断是否可以覆盖,如果不可以覆盖抛出异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
} else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
} else if (!beanDefinition.equals(existingDefinition)) {//bean定义不一致
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
} else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + existingDefinition + "] with [" + beanDefinition + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);//加入beanDefinitionMap中
} else {//否则未存在
if (hasBeanCreationStarted()) {//判断bean是否已经被创建
// 无法再修改启动时间集合元素(用于稳定迭代)
synchronized (this.beanDefinitionMap) {//对beanDefinitionMap进行加锁做更新处理
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;//更新缓存
removeManualSingletonName(beanName);
}
} else {//否则直接添加即可
// 仍处于启动注册阶段
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
//清除在冻结配置的情况下缓存bean定义名称数组
this.frozenBeanDefinitionNames = null;
}
//如果已经存在bean定义或者单例缓存中已经存在
if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);//重置bean定义
} else if (isConfigurationFrozen()) {
clearByTypeCache();//删除关于按类型映射的任何假设
}
}

14.发送 bean 注册事件

fireComponentRegistered

getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
//为给定bean创建一个新的BeanComponentDefinition。
public BeanComponentDefinition(BeanDefinitionHolder beanDefinitionHolder) {
super(beanDefinitionHolder);
List<BeanDefinition> innerBeans = new ArrayList<>();
List<BeanReference> references = new ArrayList<>();
PropertyValues propertyValues = beanDefinitionHolder.getBeanDefinition().getPropertyValues();
for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {//遍历所有的属性
Object value = propertyValue.getValue();
if (value instanceof BeanDefinitionHolder) {//如果是Bean定义持有对象
innerBeans.add(((BeanDefinitionHolder) value).getBeanDefinition());
} else if (value instanceof BeanDefinition) {//如果是Bean定义类型
innerBeans.add((BeanDefinition) value);
} else if (value instanceof BeanReference) {//如果是引用类型
references.add((BeanReference) value);
}
}
this.innerBeanDefinitions = innerBeans.toArray(new BeanDefinition[0]);
this.beanReferences = references.toArray(new BeanReference[0]);
}
public void fireComponentRegistered(ComponentDefinition componentDefinition) {
this.eventListener.componentRegistered(componentDefinition);
}

1.2.8.5 prepareBeanFactory(beanFactory)

准备 bean 工厂,以便在本文中使用

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 告诉内部bean工厂使用上下文的类加载器等。
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// 使用上下文回调配置bean工厂
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
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接口未在普通工厂中注册为可解析类型。
//MessageSource作为bean注册(并找到自动连接)。
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 将用于检测内部bean的早期后处理器注册为ApplicationListener。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 检测LoadTimeWeaver并准备编织(如果发现)
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// 为类型匹配设置临时类加载器
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册默认的环境bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}

1.2.8.6 postProcessBeanFactory(beanFactory)

允许在上下文子类中对 bean 工厂进行后处理。

//在当前普通应用没做任何处理,如果是web应用设置servletContext相关内容
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//empty
}

1.2.8.7 invokeBeanFactoryPostProcessors(beanFactory)

调用在上下文中注册为 bean 的工厂处理器

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//调用bean工厂后置处理器
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
//检测LoadTimeWeaver并准备编织(如果存在)(例如,通过ConfigurationClassPostProcessor注册的@Bean方法)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

调用 bean 工厂后置处理器

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// 如果有,首先调用BeanDefinitionRegistryPostProcessors
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry registry) {
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
} else {
regularPostProcessors.add(postProcessor);
}
}
//不要在这里初始化FactoryBean:我们需要保留所有常规Bean未初始化,让bean factory后处理器应用于它们!在实现优先顺序,以及其他。
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessor。
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 接下来,调用实现Ordered的BeanDefinitionRegistryPostProcessor。
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// 最后,调用所有其他BeanDefinitionRegistryPostProcessor,直到不再出现其他BeanDefinitionRegistryPostProcessor。
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}
// 现在,调用到目前为止处理的所有处理器的postProcessBeanFactory回调。
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// 调用在上下文实例中注册的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 不要在这里初始化FactoryBean:我们需要保留所有常规Bean未初始化,让bean factory后处理器应用于它们!
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 将实现PriorityOrdered、Ordered和其他功能的BeanFactory后处理器分开。
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// 跳过-已在上述第一阶段处理
} 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 {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先,调用实现PriorityOrdered的BeanFactory后处理器。
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 接下来,调用实现Ordered的BeanFactory后处理器。
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
//排序处理
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后,调用所有其他BeanFactory后处理器。
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
//调用非排序的bean工厂后置处理器
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
//清除缓存的合并bean定义,因为后处理器可能修改了原始元数据,例如替换值中的占位符
beanFactory.clearMetadataCache();
}

1.2.8.8 registerBeanPostProcessors(beanFactory)

注册拦截 bean 创建的 bean 处理器。

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
//注册BeanPostProcessorChecker,在bean是在BeanPostProcessor实例化期间创建的,即一个bean没有资格被所有BeanPostProcessor处理。
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 将实现PriorityOrdered、Ordered和其他功能的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);
}
}
// 首先,注册实现PriorityOrdered的BeanPostProcessor。
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 接下来,注册实现Ordered的BeanPostProcessor。
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 现在,注册所有常规BeanPostProcessor。
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后,重新注册所有内部BeanPostProcessor。
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 将用于检测内部bean的后处理器重新注册为ApplicationListener,将其移动到处理器链的末端(用于获取代理等)。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

1.2.8.9 beanPostProcess.end()

默认空实现,记录步骤的状态,以及可能的其他指标,如执行时间。一旦结束,不允许更改步骤状态。

1.2.8.10 initMessageSource()

初始化国际化信息源,这里先不展开

1.2.8.11 initApplicationEventMulticaster()

为此上下文初始化事件广播

protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//判断当前容器是否存在applicationEventMulticaster
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
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.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}

1.2.8.12 onRefresh()

初始化特定上下文子类中的其他特殊 bean(默认空实现)

protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}

1.2.8.13 registerListeners()

检查侦听器 bean 并注册它们

protected void registerListeners() {
// 首先注册静态指定的侦听器
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 不要在这里初始化FactoryBean:我们需要保留所有常规Bean 未初始化以允许后处理器应用于它们!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 发布早期应用程序事件
// 现在我们终于有了一个multicaster
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}

1.2.8.14 finishBeanFactoryInitialization(beanFactory)

实例化所有剩余的(非懒加载初始化)单例

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化 conversion service 在当前容器中(上下文)
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
//如果没有BeanFactoryPostProcessor,请注册默认嵌入值解析器
//(例如PropertySourcesPlaceholderConfigurer bean)在以下任何时间之前注册:
//此时,主要用于注解属性值中的分辨率。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 尽早初始化LoadTimeWeaverAware bean,以便尽早注册它们的转换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用临时类加载器进行类型匹配。
beanFactory.setTempClassLoader(null);
// 允许缓存所有bean定义元数据,不需要进一步更改。
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非懒加载初始化)单例。
beanFactory.preInstantiateSingletons();
}

实例化所有的 singletons bean (除了 lazy-init 外)

public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// 获取所有的beanDefinitionNames
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有非懒加载单例bean的初始化
for (String beanName : beanNames) {
//获取RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {//非抽象且单例且非懒加载
if (isFactoryBean(beanName)) {//如果是FactoryBean
//FactoryBean:由BeanFactory中使用的对象实现的接口它们本身就是单个对象的工厂。
//如果bean实现了这一点接口,它被用作对象暴露的工厂,而不是直接作为bean实例,该实例将自身公开。
//在获取bean前在beanName加上'&'前缀
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,getAccessControlContext());
} else {
isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {//获取该bean
getBean(beanName);//核心方法
}
}
} else {
getBean(beanName);//核心方法
}
}
}
// 触发所有适用bean的初始化后回调 如果我们定义的 bean 是实现了 SmartInitializingSingleton 接口的,那么在这里得到回调
for (String beanName : beanNames) {
//通过beanname获取bean
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton smartSingleton) {
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);
//后置处理
smartSingleton.afterSingletonsInstantiated();
smartInitialize.end();
}
}
}

获取单例 bean 的核心方法 getBean

public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}

doGetBean

protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
// 转换beanName判断是否以&开头的FactoryBean
String beanName = transformedBeanName(name);
Object beanInstance;//bean实例(最终返回)
// 检查单例缓存中手动注册的单例(用于判断是否已经创建过)
Object sharedInstance = getSingleton(beanName);
//当args不为空将创建bean
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
//判断指定的单例bean当前是否正在创建中
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
} else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 获取给定bean实例的对象,可以是bean实例本身,也可以是FactoryBean中创建的对象。
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
//如果我们已经在创建这个bean的Prototype类型实例,则抛出异常:
//往往是因为陷入了循环引用
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 检查 bean definition 是否存在当前容器中
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 当前容器未找到向父容器查找
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory abf) {
return abf.doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
} else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
} else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
//如果bean能够正常创建 添加进alreadyCreated缓存
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
//
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);
try {
//bean的所需类型
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// 保证当前bean所依赖的bean的初始化
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
//确定指定的依赖bean是否已注册为依赖于给定bean或其任何可传递依赖项,否则抛出循环依赖
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);
} catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 如果bean的作用域是single类型
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
//(核心方法)创建bean
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
//出现异常销毁bean
destroySingleton(beanName);
throw ex;
}
});
//否则
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
//如果bean的作用域是Prototype类型
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);
}
//否则根据bean的作用域进行创建
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();
}
}
// 对bean类型进行检查
return adaptBeanInstance(name, beanInstance, requiredType);
}

createBean

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;

// 确保bean 字节码在这一点上得到了解决
// 如果是动态解析的类,请克隆bean定义
// 不能存储在共享合并bean定义中。
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 准备方法重写
try {
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
}

try {
//让BeanPostProcessors有机会返回代理,而不是目标bean实例。
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);
}
}
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {//如果是single类型将其
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {//不是factoryBean,创建bean实例
//重点关注
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// 允许后处理器修改合并的bean定义
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;
}
}
//预先地缓存单例,以便能够解析循环引用(bean的提前曝光)
//即使是由BeanFactoryAware等生命周期接口触发。
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");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// 初始化bean实例
Object exposedObject = bean;
try {
//装配bean的属性
populateBean(beanName, mbd, instanceWrapper);
//处理bean的创建完成的回调
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);
if (earlySingletonReference != null) {
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.");
}
}
}
}

// 注册bean的disposable回调
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}

创建 bean 实例

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 确保已加载了该class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
//检查类的访问权限
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());
}
//有指定的实例提供者
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//采用工厂方法实例化
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// 如果不是第一次创建,比如第二次创建 prototype bean。
// 这种情况下,我们可以从第一次创建知道,采用无参构造函数,还是构造函数依赖注入 来完成实例化
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
//构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
} else {
//无参构造函数
return instantiateBean(beanName, mbd);
}
}

// 自动注入的候选构造器
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 判断是否采用有参构造函数
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);
}

// 无需特殊处理:只需不使用arg构造函数即可。
return instantiateBean(beanName, mbd);
}
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果没有重写,不用CGLIB重写该类。
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;//构造器
synchronized (bd.constructorArgumentLock) {//加锁
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
//获取类class
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {//如果是接口抛出异常
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
constructorToUse = clazz.getDeclaredConstructor();//获取公开的构造器
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
} catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//通过beanUtils进行反射实例化
return BeanUtils.instantiateClass(constructorToUse);
}
// 如果有重写的方法,采用cglib生成子类
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

此时 bean 已经实例化完成,开始进行属性的注入,回到上面的的populateBean 方法

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {//如果bean为空确有属性需要注入则抛出异常
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
} else {
// 否则不需要任何注入直接返回
return;
}
}
//给实例化WareBean后处理器修改,这可以用来设置属性之前bean的状态
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}

PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 根据autowire按名称添加特性值(如果适用)如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 根据autowire按类型添加特性值(如果适用)
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// 这里有个非常有用的 BeanPostProcessor 进到这里: AutowiredAnnotationBeanPostProcessor
// 对采用 @Autowired、@Value 注解的依赖进行设值,这里的内容也是非常丰富的
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
pvs = pvsToUse;
}
}
if (needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
checkDependencies(beanName, mbd, filteredPds, pvs);
}

if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

调用各种回调

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
//调用回调
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 快速检查没有完整单例锁的现有实例
Object singletonObject = this.singletonObjects.get(beanName);
//判断指定的单例bean当前是否正在创建中(在整个工厂内)。
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//加锁保证有且只有一条线程创建成功
synchronized (this.singletonObjects) {
// 没错这里就是解决依赖循环应用的关键了
// 在完整单例锁中一致创建早期引用
singletonObject = this.singletonObjects.get(beanName);//一级缓存中查找
if (singletonObject == null) {//一级缓存没有找到进入二级缓存查找
singletonObject = this.earlySingletonObjects.get(beanName);//二级缓存中查找
if (singletonObject == null) {//二级缓存没有找到意味着bean还没有实例化,尝试进行实例化
//获取该bean的bean工厂
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {//如果该bean工厂存在则进行获取bean
singletonObject = singletonFactory.getObject();//从bean工厂中s
this.earlySingletonObjects.put(beanName, singletonObject);//加入二级缓存
this.singletonFactories.remove(beanName);//从一级缓存中移除
}
}
}
}
}
}
return singletonObject;//返回bean实例
}

1.2.8.15 finishRefresh()

最后一步:发布相应的事件

DefaultSingletonBeanRegistry

2.循环依赖分析

3.相关参考资料

Spring 核心 IOC 的源码分析


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK