源码学习-Spring 源码分析

image.png

简介

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 新建立maven项目

1
2
3
4
5
6
7
8
<?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>
1
2
3
public interface MessageService {
public String getMessage();
}
1
2
3
4
5
6
7
public class MessageServiceImpl implements MessageService {
@Override
public String getMessage() {
System.out.println("get message ......");
return "MESSAGE";
}
}
1
2
3
4
5
6
7
8
9
10
11
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 调用应用上下文构造方法

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

1.2.2 构造方法

1
2
3
4
5
6
7
8
//构造方法
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父类构造方法具体是什么

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
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环境配置信息

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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 (预刷新处理)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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工厂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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工厂

1
2
3
4
5
6
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
protected BeanFactory getInternalParentBeanFactory() {
return (getParent() instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) getParent()).getBeanFactory() : getParent());
}

默认beanFactory(DefaultListableBeanFactory)

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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子类实例化策略
}
}

image.png
设置父类bean工厂

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
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的方式在类路径下加载,所以会使用的加载器是

1
2
3
4
5
6
7
8
9
10
11
12
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定义

1
2
3
4
5
6
7
8
9
10
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.加载配置的文件

1
2
3
4
5
6
7
8
9
10
11
12
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匹配加载的路径(类路径和绝对路径)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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.根据输入的路径进行匹配加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 = "*/";
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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对象

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//我们使用的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文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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

1
2
3
4
5
6
7
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;
}
1
2
3
4
5
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//注册bean定义
doRegisterBeanDefinitions(doc.getDocumentElement());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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配置的类型进行区分加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//	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定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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

1
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//为给定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]);
}
1
2
3
public void fireComponentRegistered(ComponentDefinition componentDefinition) {
this.eventListener.componentRegistered(componentDefinition);
}

1.2.8.5 prepareBeanFactory(beanFactory)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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工厂进行后处理。

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

1.2.8.7 invokeBeanFactoryPostProcessors(beanFactory)

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

1
2
3
4
5
6
7
8
9
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工厂后置处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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处理器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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()

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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(默认空实现)

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

1.2.8.13 registerListeners()

检查侦听器bean并注册它们

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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外)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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

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

doGetBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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;
// 初始化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;
}
//否则如果当前bean还有依赖的bean则进行获取并
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
//实际依赖的bean如果创建好了就注入
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实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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);
}
}

调用各种回调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

1.3 流程图

对象生命周期

五大阶段

  1. 创建准备:

通过获取注解配置、XML配置的相关Bean定义

  1. 创建实例:

通过反射进行实例化对象,根据配置情况调用 Bean 构造方法或工厂方法实例化 Bean

  1. 依赖注入:

利用依赖注入完成 Bean 中所有属性值的配置注入,如果存在依赖则寻找依赖,通过三级缓存,提前曝光方式解决

Aware接口

  • 如果 Bean 实现了 BeanNameAware 接口,则 Spring 调用 Bean 的 setBeanName() 方法传入当前 Bean 的 id 值。
  • 如果 Bean 实现了 BeanFactoryAware 接口,则 Spring 调用 setBeanFactory() 方法传入当前工厂实例的引用。
  • 如果 Bean 实现了 ApplicationContextAware 接口,则 Spring 调用 setApplicationContext() 方法传入当前 ApplicationContext 实例的引用。

BeanPostProcessor 前置处理

如果 BeanPostProcessor 和 Bean 关联,则 Spring 将调用该接口的预初始化方法 postProcessBeforeInitialzation() 对 Bean 进行加工操作,Spring 的 AOP 就是利用它实现的。

初始化方法

如果 Bean 实现了 InitializingBean 接口,则 Spring 将调用 afterPropertiesSet() 方法。
如果在配置文件中通过 init-method 属性指定了初始化方法,则调用该初始化方法。

BeanPostProcessor 后置处理

如果 BeanPostProcessor 和 Bean 关联,则 Spring 将调用该接口的初始化方法 postProcessAfterInitialization()。此时,Bean 已经可以被应用系统使用了。

  1. 容器缓存:
  • 如果指定了该 Bean 的作用范围为 scope=”singleton”,则将该 Bean 放入 Spring IOC 的缓存池中,将触发 Spring 对该 Bean 的生命周期管理;
  • 如果指定了该 Bean 的作用范围为 scope=”prototype”,则将该 Bean 交给调用者,调用者管理该 Bean 的生命周期,Spring 不再管理该 Bean。
  1. 销毁实例:

如果 Bean 实现了 DisposableBean 接口,则 Spring 会调用 destory() 方法将 Spring 中的 Bean 销毁;如果在配置文件中通过 destory-method 属性指定了 Bean 的销毁方法,则 Spring 将调用该方法对 Bean 进行销毁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

public class SpringBeanLife implements BeanNameAware, ApplicationContextAware, InitializingBean, DisposableBean {

private String name;

public SpringBeanLife() {
System.out.println("第一步:实例化类");
}

public void setName(String name) {
System.out.println("第二步:设置属性");
this.name = name;
}

@Override
public void setBeanName(String s) {
System.out.println("第三步:设置bean的名称也就是spring容器中的名称,也就是id值" + name);
}

@Override
public void setApplicationContext(ApplicationContext applicationContext) {
System.out.println("第四步:了解工厂信息ApplicationContext");
}
//第五步执行初始化之前执行的方法
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("第六步:属性设置后执行的方法");
}

public void setup() {
System.out.println("第七步:执行自己配置的初始化方法");
}

//第八步执行初始化之后执行的方法
public void biz() {
System.out.println("第九步:执行自身的业务方法");
}

@Override
public void destroy() {
System.out.println("第十步:执行spring的销毁方法");
}

public void customDestroyMethod() {
System.out.println("第十一步:执行自己配置的销毁方法");
}
}

循环依赖分析

循环依赖指的是在创建Bean的过程中,Bean A中有Bean B作为属性,而Bean B中又有Bean作为属性,此时创建Bean A过程中需要先去创建Bean B,而创建Bean B的过程中又发现需要先创建Bean A,造型循环依赖。

三种循环依赖

  • 构造器的循环依赖:这种依赖spring是处理不了的,直接抛出BeanCurrentlylnCreationException异常。
  • 单例模式下的setter循环依赖:通过“三级缓存”处理循环依赖,能处理。
  • 非单例循环依赖:无法处理。原型(Prototype)的场景是不支持循环依赖的,通常会走到AbstractBeanFactory类中下面的判断,抛出异常。
    1
    2
    3
    if (isPrototypeCurrentlyInCreation(beanName)) {  
    throw new BeanCurrentlyInCreationException(beanName);
    }

三级对象缓存

那Spring中是如何解决这个问题的?我们先来看看在getSingleton获取bean的方法

我们需要先了解一下spring的三级缓存

  • 一级缓存为:singletonObjects;中缓存的是已经经历了完整生命周期的bean对象。

  • 二级缓存为:earlySingletonObjects;比 singletonObjects 多了一个 early ,表示缓存的是早期的 bean对象。早期指的是 Bean 的生命周期还没走完就把这个 Bean 放入了 earlySingletonObjects。

  • 三级缓存为:singletonFactories;中缓存的是 ObjectFactory,表示对象工厂,主要用来去生成原始对象进行了 AOP之后得到的「代理对象」,在每个 Bean 的生成过程中,都会提前暴露一个工厂,这个工厂可能用到,也可能用不到,如果没有出现循环依赖依赖本 bean,那么这个工厂无用,本 bean 按照自己的生命周期执行,执行完后直接把本 bean 放入 singletonObjects 中即可,如果出现了循环依赖依赖了本 bean,则另外那个 bean 执行 ObjectFactory 提交得到一个 AOP 之后的代理对象(如果有 AOP 的话,如果无需 AOP ,则直接得到一个原始对象)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public Object getSingleton(String beanName) {
//缺省为允许bean提前曝光
return getSingleton(beanName, true);
}
//判断bean是否正在创建中
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
//获取bean方法
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 快速检查没有完整单例实例
Object singletonObject = this.singletonObjects.get(beanName);
// 判断指定的单例bean当前是否正在创建中(在整个工厂内)。
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//如果一级缓存中没有且当前bean正在创建中,则尝试去二级缓存中获取
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工厂中获取该bean,主要此时的bean并没有完成创建,相当于只是得到这个bean的引用而以,打破bean的循环依赖
this.earlySingletonObjects.put(beanName, singletonObject);//加入二级缓存
this.singletonFactories.remove(beanName);//从三级级缓存中移除
}
}
}
}
}
}
return singletonObject;//返回bean实例
}

既然构成了循环那我们只要打破其中一个路径即可阻断循环,spring也是这么处理的

结论:Spring中通过三级缓存解决循环依赖问题,通过提前曝光bean在二级缓存(earlySingletonObjects)中,需要引用的对象之间可以在缓存中获取,阻断了循环去创建的发生。

singletonFactories

既然一个earlySigletonObjects缓存就可以解决循环依赖的问题了,为什么还需要singletonFactories呢?

这个时候我们就要来考虑一下这种情况:

如果对象A的原始对象注入对象B(对象B提前曝光了)的属性之后,A的原始对象进行AOP产生了一个代理对象,此时对于A而言A的对象其实应该是他AOP后的对象,而B的属性对于的是A的原始对象,并不是AOP后的代理对象,此时出现问题。

我们先看看singletonFactories缓存是什么时候加入的

1.doCreateBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {//如果是single类型将其在factoryBean缓存中移除
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;
}
}
//这里主要是为了获取当前这个正在创建的对象是否允许提前曝光,如果允许,则直接添加一个 ObjectFactory 到三级缓存
//其中this.allowCircularReferences的默认值是true,也就是说默认允许提前曝光来解决循环依赖的问题
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的EarlyBeanReference,然后加入三级缓存
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充属性
populateBean(beanName, mbd, instanceWrapper);
//处理bean的创建完成的回调,执行初始化(如afterPropertiesSet)方法且创建代理
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);
}
}
//如果是提前曝光的bean则尝试去一级缓存看看有没有实例化好
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
//如果一级缓存中有了,则改bean已经初始化好了
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
//否则判断它是否有依赖的bean,有则尝试去获取实际依赖的bean
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 {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}

在上面的代码中我们可以看到,在创建当前bean的实例后(只是实例化了还没有初始化),判断是否可以提前曝光,如果可以提前曝光则把当前bean的ObjectFactory(包装了当前bean)放入三级缓存中去(singletonFactories)。

为什么不直接把这个bean引用放进去呢?回到上面我们考虑的情况,如果创建的 Bean 是有代理的,那么注入的就应该是代理 Bean,而不是原始的 Bean。但是 Spring 一开始并不知道 Bean 是否会有循环依赖,通常情况下(没有循环依赖的情况下),Spring 都会在完成填充属性,并且执行完初始化方法之后再为其创建代理。但是,如果出现了循环依赖的话,Spring 就不得不为其提前创建代理对象,否则注入的就是一个原始对象,而不是代理对象。因此,这里就涉及到应该在哪里提前创建代理对象?
Spring 的做法就是在 ObjectFactory 中去提前创建代理对象。它会执行 getObject() 方法来获取到 Bean

2.获取bean的早期引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//获取提前访问指定bean的引用
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
//isSynthetic返回此bean定义是否为“合成”,即不是由应用程序本身定义的。
//hasInstantiationAwareBeanPostProcessors是但其bean的所有bpp
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
// 如果需要代理,这里会返回代理对象;否则返回原始对象
exposedObject = bp.getEarlyBeanReference(exposedObject, beanName);
}
}
//返回提前曝光的bean引用
return exposedObject;
}

3.创建代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//获取Bean的早期引用
public Object getEarlyBeanReference(Object bean, String beanName) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
// 记录已被代理的对象
this.earlyProxyReferences.put(cacheKey, bean);
return wrapIfNecessary(bean, beanName, cacheKey);
}
//获取缓存的key
//FACTORY_BEAN_PREFIX = "&";
protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
if (StringUtils.hasLength(beanName)) {
return (FactoryBean.class.isAssignableFrom(beanClass) ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName);
} else {
return beanClass;
}
}
//对早期引用进行包装
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

// 为切面创建代理类
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}

this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

4.添加进三级缓存

从doCreateBean代码第十三行中可以看到,传递过来的是一个匿名函数

1
2
3
4
5
6
7
8
9
10
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {//确保一级缓存没有该bean
this.singletonFactories.put(beanName, singletonFactory);//添加进三级缓存
this.earlySingletonObjects.remove(beanName);//确保一级缓存没有该bean
this.registeredSingletons.add(beanName);
}
}
}

无法解决的循环依赖问题

  • 在主bean中通过构造函数注入所依赖的bean。在上面的分析中都是预先执行构造函数获取实例,再将ObjectFactory加入三级缓存,如果是通过构造器注入,此时缓存中还没有对应的缓存,则实例化无法完成,失败。

总结

当存在循环依赖时,主bean对象不能通过构造函数的方式注入所依赖的bean对象,而所依赖的bean对象则不受限制,即可以通过三种注入方式的任意一种注入主bean对象。

如果主bean对象通过构造函数方式注入所依赖的bean对象,则无论所依赖的bean对象通过何种方式注入主bean,都无法解决循环依赖问题,程序无法启动。(其实在主bean加上@Lazy也能解决)

相关参考资料

Spring核心IOC的源码分析


源码学习-Spring 源码分析
https://mikeygithub.github.io/2022/02/28/yuque/源码学习-Spring 源码分析/
作者
Mikey
发布于
2022年2月28日
许可协议