0%

Spring Boot 启动流程

Spring Boot应用打包

在编写spring boot 项目的时候往往会在pom的build 部分内加入

1
2
3
4
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

其作用就是重新组织资源 使最终的结果物 无论是jar形式的还是 war形式的 都能 通过java -jar ***.jar(war)的命令启动。

在通过maven 打包的时候

首先按照会正常的流程编译,之后

spring-boot-maven-plugin 插件 会介入进行repackage

1
2
[INFO] --- spring-boot-maven-plugin:2.2.6.RELEASE:repackage (repackage) @ demo ---
[INFO] Replacing main artifact with repackaged archive

根据在pom 中 packaging 指定的类型不同 jar/war 重新组织文件的结构和内容

  1. 如果是war类型的

    对artifacts进行解压后会有如下的文件结构

    META-INF/ MAINFEST.MF

    META-INF/maven/com/example/demo/pom.properties

    META-INF/maven/com/example/demo/pom.xml

    WEB-INF/classes/*

    WEB-INF/lib/*

    org/springframework/boot/loader/*

    其中org/springframework/boot/loader/* 所代表的是下面这个包内的内容

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader</artifactId>
</dependency>

其作用是引导Spring Boot应用加载资源

同时会修改 MAINFEST.MF 的内容 ,值得注意的是Main class 并不是在程序里面写的入口类,而是Spring Boot提供的一个入口类

1
2
3
4
5
6
7
8
9
10
Manifest-Version: 1.0
Created-By: Maven Archiver 3.4.0
Build-Jdk-Spec: 11
Implementation-Title: demo
Implementation-Version: 0.0.1-SNAPSHOT
Main-Class: org.springframework.boot.loader.archive.Archive.WarLauncher
Start-Class: com.example.demo.DemoApplication
Spring-Boot-Version: 2.2.6.RELEASE
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
  1. 如果是jar 类型的

    对jar进行解压后会有如下的文件结构

    META-INF/ MAINFEST.MF

    META-INF/maven/com/example/demo/pom.properties

    META-INF/maven/com/example/demo/pom.xml

    BOOT-INF/classes/*

    BOOT-INF/lib/*

    org/springframework/boot/loader/*

    差异点有

    把WEB-INF 替换为 BOOT-INF

    MAINFEST.MF 中的Main-Class 为org.springframework.boot.loader.JarLauncher

Spring Boot项目启动

首先会加载 main-class 指定类的main方法。然后由其调用start-class 中的main方法

Main-Class部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected final Archive createArchive() throws Exception {
ProtectionDomain protectionDomain = getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
String path = (location != null) ? location.getSchemeSpecificPart() : null;
if (path == null) {
throw new IllegalStateException("Unable to determine code source archive");
}
File root = new File(path);
if (!root.exists()) {
throw new IllegalStateException("Unable to determine code source archive from " + root);
}
return (root.isDirectory() ? new ExplodedArchive(root) : new JarFileArchive(root));
}
  • Launcher

    这个类的作用是加载程序。JarLauncher 和 WarLauncher 都是继承于ExecutableArchiveLauncher

    在ExecutableArchiveLauncher的构造方法中调用

    Launcher#createArchive

    根据当前class的位置是在文件中还是文件夹中 判断程序jar类型的还是war类型的

    如果是jar类型的 文件组织方式是 /BOOT-INF/lib /BOOT-INF/classes

    如果是war类型的 文件的组织方式是 WEB-INF/lib WEB-INF/classes

    生成对应的 JarFileArchive ExplodedArchive 供后续的文件遍历使用

    父类加载完成 子类的构造函数中(JarLauncher / WarLauncher)中并没有什么内容

    举个例子

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class Main {
    public static void main(String[] args) throws Exception {
    ProtectionDomain protectionDomain = Main.class.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
    System.out.println(location);
    String path = (location != null) ? location.getSchemeSpecificPart() : null;
    System.out.println(path);
    }
    }

    输出的结果是

    file:/Users/andrewchen1/Downloads/demo/target/classes/
    /Users/andrewchen1/Downloads/demo/target/classes/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) throws Exception {
new JarLauncher().launch(args);
}
protected void launch(String[] args) throws Exception {
JarFile.registerUrlProtocolHandler();
ClassLoader classLoader = createClassLoader(getClassPathArchives());
launch(args, getMainClass(), classLoader);
}
@Override
protected List<Archive> getClassPathArchives() throws Exception {
List<Archive> archives = new ArrayList<>(this.archive.getNestedArchives(this::isNestedArchive));
postProcessClassPathArchives(archives);
return archives;
}
  • getClassPathArchives

    对于jar 通过jarEntry 遍历jar中的所有内容 将 BOOT-INF/classes/ 和 BOOT-INF/lib/路径下的内容返回到list中

    对于explored war 通过遍历root path 下的所有内容 将WEB-INF/classes/和WEB-INF/lib/, WEB-INF/lib-provided/

    jar

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public List<Archive> getNestedArchives(EntryFilter filter) throws IOException {
    List<Archive> nestedArchives = new ArrayList<>();
    for (Entry entry : this) {
    if (filter.matches(entry)) {
    nestedArchives.add(getNestedArchive(entry));
    }
    }
    return Collections.unmodifiableList(nestedArchives);
    }
    // 能 for (Entry entry : this) 的原因是 JarFileArchive的超类Archive 实现了Iterable<Archive.Entry> 接口

    @Override
    public Iterator<Entry> iterator() {
    return new EntryIterator(this.jarFile.entries());
    }

    // EntryIterator # hasNext方法
    public boolean hasNext() {
    return this.enumeration.hasMoreElements();
    }

    explored war

    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
    @Override
    public List<Archive> getNestedArchives(EntryFilter filter) throws IOException {
    List<Archive> nestedArchives = new ArrayList<>();
    for (Entry entry : this) {
    if (filter.matches(entry)) {
    nestedArchives.add(getNestedArchive(entry));
    }
    }
    return Collections.unmodifiableList(nestedArchives);
    }
    // 能 for (Entry entry : this) 的原因是 JarFileArchive的超类Archive 实现了Iterable<Archive.Entry> 接口
    @Override
    public Iterator<Entry> iterator() {
    return new FileEntryIterator(this.root, this.recursive);
    }
    // FileEntryIterator # hasNext方法
    @Override
    public Entry next() {
    if (this.current == null) {
    throw new NoSuchElementException();
    }
    File file = this.current;
    if (file.isDirectory() && (this.recursive || file.getParentFile().equals(this.root))) {
    this.stack.addFirst(listFiles(file));
    }
    this.current = poll();
    String name = file.toURI().getPath().substring(this.root.toURI().getPath().length());
    return new FileEntry(name, file);
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) throws Exception {
new JarLauncher().launch(args);
}
protected void launch(String[] args) throws Exception {
JarFile.registerUrlProtocolHandler();
ClassLoader classLoader = createClassLoader(getClassPathArchives());
launch(args, getMainClass(), classLoader);
}
protected ClassLoader createClassLoader(List<Archive> archives) throws Exception {
List<URL> urls = new ArrayList<>(archives.size());
for (Archive archive : archives) {
urls.add(archive.getUrl());
}
return createClassLoader(urls.toArray(new URL[0]));
}
protected ClassLoader createClassLoader(URL[] urls) throws Exception {
return new LaunchedURLClassLoader(urls, getClass().getClassLoader());
}

这部分的内容不多 就是创建一个类加载器 加载资源

//TODO classload 坑等待填 好怕怕的类加载器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static void main(String[] args) throws Exception {
new JarLauncher().launch(args);
}
protected void launch(String[] args) throws Exception {
JarFile.registerUrlProtocolHandler();
ClassLoader classLoader = createClassLoader(getClassPathArchives());
launch(args, getMainClass(), classLoader);
}
protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception {
Thread.currentThread().setContextClassLoader(classLoader);
createMainMethodRunner(mainClass, args, classLoader).run();
}
protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) {
return new MainMethodRunner(mainClass, args);
}
public MainMethodRunner(String mainClass, String[] args) {
this.mainClassName = mainClass;
this.args = (args != null) ? args.clone() : null;
}
public void run() throws Exception {
Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName);
Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
mainMethod.invoke(null, new Object[] { this.args });
}

Start-Class 部分

SpringApplication.run(Application.class, args);

创建SpringApplication

  1. 确定resourceLoader (which is null)
  2. 确定primarySource (就是我们写main方法的那个类)
  3. 确定WebApplicationType (通过Class.ForName方法确认ClassLoader 中是否加载过特定的类,通过这个方法确定WebApplicationType)
  4. 通过spring.factories的方式获得要加载的ApplicationContextInitializer和ApplicationListener
  5. 确定MainApplicationClass (这个获取的方式很有意思 是通过生成一个RuntimeExcetpion的方式通过获得strackTrace 得到有main方法的那个类)

触发SpringApplication 的run方法

  1. 触发所有的ApplicationListener的starting方法

  2. 解析命令行形式的参数,解析成source内容,放到Enviorment 中

  3. 解析Enviorment中profile的内容

  4. 触发所有的ApplicationListener的environmentPrepared方法

  5. 根据WebApplicationType 获得要生成的ApplicationContext,要生成的ApplicationContext的父类GenericApplicationContext的构造方法中会生成DefaultListableBeanFactory

  6. 准备ApplicationContext

    1. 设置ApplicationContext的Enviorment
    2. 设置beanNameGenerator,resourceLoader
    3. 触发ApplicationContextInitializer, 像Apollo,spring cloud config center就是在这个时候获取远端的config,把它加入到Enviorment中
    4. 触发ApplicationListener的contextPrepared的方法
    5. 设置ConfigurableListableBeanFactory
    6. 触发ApplicationListener的contextLoaded方法
  7. 刷新Context

    1. prepareRefresh

      1. 初始化earlyApplicationListeners,初始值来自于applicationListeners
      2. 初始化earlyApplicationEvents
    2. obtainFreshBeanFactory

      1. loadBeanDefinitions
        1. loadBeanDefinitions
    3. prepareBeanFactory

      1. 设置factory的beanClassLoader,BeanExpressionResolver(类解析器),ResourceEditorRegistrar(配置解析器)
      2. 设置factory 哪些类(这些类生成了特定的接口 比方说ApplicationContextAware)是不用生成bean的
    4. postProcessBeanFactory

      在beanFactory生成之后

    5. invokeBeanFactoryPostProcessor

注册Bean

解析Bean

BeanDefinitionReaderUtils#registerBeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {

// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}

DefaultListableBeanFactory#registerBeanDefinition

Bean 是注册在beanDefinitionMap 这个Map中的

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
@Override
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();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}

BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
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)) {
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);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
// 保护beanDefinitionMap
synchronized (this.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 {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}

if (existingDefinition != null || containsSingleton(beanName)) {
resetBeanDefinition(beanName);
}
}

自定义标签解析

如何使用

  • 定义一个POJO

    1
    2
    3
    4
    5
    6
    @Data
    public class User {
    private Long id;
    private String userName;
    private String email;
    }
  • 定义标签的XSD user.xsd

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <?xml version="1.0"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://blog.andrewchen1.top/user"
    elementFormDefault="qualified">
    <xs:element name="user">
    <xs:complexType>
    <xs:attribute name="id" type="xs:string"/>
    <xs:attribute name="userName" type="xs:string"/>
    <xs:attribute name="email" type="xs:string"/>
    </xs:complexType>
    </xs:element>
    </xs:schema>
  • 定义parse

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class UserBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
    @Override
    protected Class<?> getBeanClass(Element element) {
    return User.class;
    }

    @Override
    protected void doParse(Element element, BeanDefinitionBuilder builder) {
    String userName = element.getAttribute("userName");
    String email = element.getAttribute("email");
    Long id = Long.valueOf(element.getAttribute("id"));

    builder.addPropertyValue("userName", userName);
    builder.addPropertyValue("email", email);
    builder.addPropertyValue("id", id);
    }
    }
  • 注册parse handler

    1
    2
    3
    4
    5
    6
    public class MyNamespaceHandler extends NamespaceHandlerSupport {
    @Override
    public void init() {
    registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
    }
    }
  • 在META-INF/spring.handler中 (这个位置是代码写死的)

    http://blog.andrewchen1.top/user=com.example.demo.MyNamespaceHandler

  • 在META-INF/Spring.schemas中 (这个位置是代码写死的)

    http://blog.andrewchen1.top/user.xsd=user.xsd

1
2
3
4
5
6
7
8
9
10
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:myname="http://blog.andrewchen1.top/user"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://blog.andrewchen1.top/user
http://blog.andrewchen1.top/user.xsd
">
<user id = "1" name = "andrew" email = "andrew@andrewchen1.top"/>
</beans>

实现

BeanDefinitionParserDelegate#parseCustomElement

1
2
3
4
5
6
7
8
9
10
11
12
13
@Nullable
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
String namespaceUri = getNamespaceURI(ele);
if (namespaceUri == null) {
return null;
}
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

DefaultNamespaceHandlerResolver#resolve

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
@Nullable
public NamespaceHandler resolve(String namespaceUri) {
Map<String, Object> handlerMappings = getHandlerMappings();
Object handlerOrClassName = handlerMappings.get(namespaceUri);
if (handlerOrClassName == null) {
return null;
}
else if (handlerOrClassName instanceof NamespaceHandler) {
return (NamespaceHandler) handlerOrClassName;
}
else {
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
}
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
namespaceHandler.init();
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
catch (ClassNotFoundException ex) {
throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
"] for namespace [" + namespaceUri + "]", ex);
}
catch (LinkageError err) {
throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
className + "] for namespace [" + namespaceUri + "]", err);
}
}
}
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
private Map<String, Object> getHandlerMappings() {
Map<String, Object> handlerMappings = this.handlerMappings;
if (handlerMappings == null) {
synchronized (this) {
handlerMappings = this.handlerMappings;
if (handlerMappings == null) {
if (logger.isTraceEnabled()) {
logger.trace("Loading NamespaceHandler mappings from [" + this.handlerMappingsLocation + "]");
}
try {
// handlerMappingsLocation 的值为META-INF/spring.handlers
Properties mappings =
PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
if (logger.isTraceEnabled()) {
logger.trace("Loaded NamespaceHandler mappings: " + mappings);
}
handlerMappings = new ConcurrentHashMap<>(mappings.size());
CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
this.handlerMappings = handlerMappings;
}
catch (IOException ex) {
throw new IllegalStateException(
"Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
}
}
}
}
return handlerMappings;
}

ListableBeanFactory 和 bean

以ListableBeanFactory 进行说明

doGetBean

bean factory 默认是lazy fetch的

AbstractBeanFactory#doGetBean

getSingleton [循环依赖 getSingleton](#getSingleton 循环依赖)

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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 如果Bean的名字是&开始的 要去掉& 然后到aliasMap找到beanName
// 比方说那么是&a&b&c&d 那么最后得到的beanName 是d
final String beanName = transformedBeanName(name);
Object bean;

// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
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 + "'");
}
// 返回对应的实例,有时候存在BeanFactory的情况下不是直接返回实例本身而是返回BeanFactory指定方法返回的实例
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 只有在单例模式的情况下才解决循环依赖,如果是原型模式的话就直接抛错。
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}

// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).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);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}

try {
// 将存储XML配置文件的GernericBeanDefinition 转化为RootBeanDefinition, 如果指定的BeanName 是子Bean的话会同时合并父类的相关属性
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// Guarantee initialization of beans that the current bean depends on.
// 比方说 a dependsOn b,b dependsOn c
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}

// Create bean instance.
// @Depends的都创建好了,可以创建自己了
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

else {
String scopeName = mbd.getScope();
final 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);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}

// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}

getSingleton 循环依赖

Spring解决循环依赖,你真的懂了吗?

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
 /**一级缓存,用于存放完全初始化好的 bean,从该缓存中取出的 bean 可以直接使用*/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/**二级缓存 存放原始的 bean 对象(尚未填充属性),用于解决循环依赖*/
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/**三级缓存 存放 bean 工厂对象,用于解决循环依赖*/
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

//getSingleton源码,DefaultSingletonBeanRegistry#getSingleton
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//先从一级缓存中获取已经实例化属性赋值完成的Bean
Object singletonObject = this.singletonObjects.get(beanName);
//一级缓存不存在,并且Bean正处于创建的过程中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//从二级缓存中查询,获取Bean的早期引用,实例化完成但是未赋值完成的Bean
singletonObject = this.earlySingletonObjects.get(beanName);
//二级缓存中不存在,并且允许创建早期引用(二级缓存中添加)
if (singletonObject == null && allowEarlyReference) {
//从三级缓存中查询,实例化完成,属性未装配完成
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
//二级缓存中添加
this.earlySingletonObjects.put(beanName, singletonObject);
//从三级缓存中移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;

返回 doGetBean

getObjectForBeanInstance

AbstractBeanFactory#getObjectForBeanInstance

得到的有可能是bean it self 但是有可能得到还是BeanFactory,所以当中要进行处理

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
// 这里的name
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

// Don't let calling code try to dereference the factory if the bean isn't a factory.
// 如果name里面有& 说明要的就是FactoryBean 那么我们直接返回FactoryBean 就好了
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 虽然name有& 但是Bean的类型不是FactoryBean 那么一定是出错了
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}

// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
// 如果bean的name里面没有& 并且 bean instance 也不是FactoryBean的实现
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
// 第三种情况 就是name 是没有& 但是得到的BeanDefinition是FactoryBean
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
//private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
// 查看根据bean 那么是不是已经找到了RootBeanDefinition 如果不是的话 构建RootBeanDefinition
// 根据Bean
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}

getMergedLocalBeanDefinition

AbstractBeanFactory#getMergedLocalBeanDefinition

要把BeanDefinition 转化为RootBeanDefinition

1
2
3
4
5
6
7
8
9
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
// 已经merge 好了
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}

AbstractBeanFactory#getMergedBeanDefinition

这时候主要要做的事情就是把parentBeanDefinition的值赋值给itself

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
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {

synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;

// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
// 是不是已经被转换成了RootBeanDefinitions了,如果不是 继续转换流程
if (mbd == null || mbd.stale) {
previous = mbd;
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}

// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(SCOPE_SINGLETON);
}

// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}

// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}

返回getObjectForBeanInstance

getObjectFromFactoryBean

AbstractBeanFactory#getObjectFromFactoryBean

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 Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
// sychronized singletonObjects
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
//执行Factory#getObject方法得到 对象
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
// 把这个BeanFactory放到singletonsCurrentlyInCreation map 中表示这个Bean正在被创建
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
// 这个Bean注册好了之后放到 factoryBeanObjectCache 中
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
// 如果不是singleton 不是单例的话
// 执行BeanFactory的get方法,然后得到的Object 执行BeanPostProcessor
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}

返回getObjectForBeanInstance

postProcessObjectFromFactoryBean

AbstractAutowireCapableBeanFactory#postProcessObjectFromFactoryBean

1
2
3
4
@Override
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}

AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

1
2
3
4
5
6
7
8
9
10
11
12
13
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {

Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

返回getObjectForBeanInstance

bean 的依赖(@DependencyOn)和循环依赖的解决

DefaultSingletonBeanRegistry#isDependent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
if (alreadySeen != null && alreadySeen.contains(beanName)) {
return false;
}
String canonicalName = canonicalName(beanName);
Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null) {
return false;
}
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
for (String transitiveDependency : dependentBeans) {
if (alreadySeen == null) {
alreadySeen = new HashSet<>();
}
alreadySeen.add(beanName);
if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
return true;
}
}
return false;
}

getSingleton

[ObjectFactory](#ObjectFactory singletonFactory)

DefaultSingletonBeanRegistry#getSingleton

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
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//同样的讲beanName放到 singletonsCurrentlyInCreation 中
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 由ObjectFactory创建完成
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}

beforeSingletonCreation

DefaultSingletonBeanRegistry#beforeSingletonCreation

检查bean name 是否singletonsCurrentlyInCreationmap中了 如果是的话抛错,否则加入进入Map中

afterSingletonCreation

DefaultSingletonBeanRegistry#afterSingletonCreation

检查bean name 是否singletonsCurrentlyInCreationmap中了 如果不是的话抛错,根据bean name 对对象进行移除

addSingleton

DefaultSingletonBeanRegistry#addSingleton

1
2
3
4
5
6
7
8
9
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
//加入的时机是ObjectFactroy 触发 getObject 的时候
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}

createBean

AbstractAutowireCapableBeanFactory#createBean

这里就是ObjectFactory#getObject 调用的内容

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
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;

// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

try {
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);
}
}
resolveBeforeInstantiation

AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}

一般在这个环节都是在处理各种的动态代理

//TODO

介绍一下一种RedLock 在遇到预期的Exception的时候自动删除锁的方式

  • 有一个注解@LockReleaseCondition,这个注解有两个属性

    1. 幂等锁的前缀

    2. 要响应的Exception的list。

  • BeanPostProcessor接口

    实现postProcessBeforeInitialization

    1
    2
    3
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    return bean;
    }

    根据bean找到对应的Class,检查Class 中每一个方法是否被@LockReleaseCondition注解修饰,将被修饰的方法放到List中。如果这个List不为empty。生成这个类的代理类,ProxyFactory proxyFactory = new ProxyFactory(bean);对list的方法中的method生成两个Advisor。一个实现ThrowsAdvice,检查抛出的Exception中是不是有注解中定义的Exception。如果有的然后在ReadLock中删除Key。第二个实现AfterReturningAdvice, 在方法结束的时候删除在ThreadLocal中的key,解决重入问题。

Spring 代理的部分](http://blog.andrewchen1.top/2020/08/30/spring-proxy/)

getSingleton

doCreateBean

AbstractAutowireCapableBeanFactory#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
91
92
93
94
95
96
97
98
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 根据指定bean使用的对应策略创建实例, 比方说工厂构造函数 etc
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
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));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}

if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
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 " +
"'getBeanNamesOfType' 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;
}
createBeanInstance

AbstractAutowireCapableBeanFactory#createBeanInstance

这个的arg是从doGetBean的args 参数来的 一般情况下可以忽略?

判断是通过什么方式构造这个bean 工厂/构造函数/setter?

提前曝光 循环依赖解决

addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

检查是不是需要进行曝光。是的话 创建一个ObjectFactoy 实例放到singletonFactories。这个ObjectFacotry和bean的加载 中的getSingleton方法中构建的ObjectFactory完全不是一回事情

  • addSingletonFactory

    DefaultSingletonBeanRegistry#addSingletonFactory

    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)) {
    this.singletonFactories.put(beanName, singletonFactory);
    this.earlySingletonObjects.remove(beanName);
    this.registeredSingletons.add(beanName);
    }
    }

  • getEarlyBeanReference

AbstractAutowireCapableBeanFactory#getEarlyBeanReference

1
2
3
4
5
6
7
8
9
10
11
12
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}

如果A和B项目相互依赖,A在populateBean的时候在BeanFactory中找B。 B不存在,也按照流程进行创建, 在populateBean的时候,getBean A,在BeanFactory中的singleonFactories找到A。触发getObejct方法。实际上会触发

AbstractAutowireCapableBeanFactory#getEarlyBeanReference这个方法

  • populateBean

    AbstractAutowireCapableBeanFactory#populateBean

    主要做的事情是

    1. 调用postProcessAfterInstantiation
    2. 根据注入类型提取依赖的bean,存入PropertyValues
    3. 应用InistantiationAwareBeanPostProcessor处理器的PostProcessPropertyValues方法。@Value和@Resource就是分别通过AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor组件的postProcessProperties方法对组建进行填充
  • initializeBean

    AbstractAutowireCapableBeanFactory#initializeBean

    1. invokeAwareMethod
    2. 触发我们在init=“”中定义的方法

ListableBeanFactory 和ApplicationContext

reflush

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
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备刷新的上下文环境
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
//初始化BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
// 对BeanFactory进行各种功能填充
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
// 子类覆盖方法做额外的处理
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
// 激活各种BeanFactory处理期
invokeBeanFactoryPostProcessors(beanFactory);

// Regis处理器ter bean processors that intercept bean creation.
// 注册拦截Bean创建的Bean
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
// 初始化应用消息广播器
initMessageSource();
// Initialize event multicaster for this context.
//初始化应用消息广播器
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
// 留给子类来初始化其他的Bean
onRefresh();

// Check for listener beans and register them.
// 在所有注册的bean中查找Listener Bean,注册到广播中
registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.
// 初始化剩下的单实例
finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.
// 完成刷新过程,通知生命周期处理器
finishRefresh();
}

prepareRefresh

步骤没有做什么

obtainFreshBeanFactory

AbstractApplicationContext#obtainFreshBeanFactory

1
2
3
4
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}

AbstractRefreshableApplicationContext#refreshBeanFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
// 定制BeanFactory,设置相关属性
customizeBeanFactory(beanFactory);
// 初始化 DodumentReader, 并进行XML文件读取和解析
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

回到reflush

prepareBeanFactory

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
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置classLoader
beanFactory.setBeanClassLoader(getClassLoader());
// 设置beanFactory的语言表达式
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

// Configure the bean factory with context callbacks.
// 增加BeanPostProcessor
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 interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 自动装配的特殊规则
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 增加@AspectJ的支持
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}

// Register default environment beans.
// 添加默认的Bean
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
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());
}
}

增加对SPEL 语言的支持

AbstractAutowireCapableBeanFactory#autowireBean

AbstractAutowireCapableBeanFactory#configureBean

AbstractAutowireCapableBeanFactory#autowire

AbstractAutowireCapableBeanFactory#autowireBeanProperties

AbstractAutowireCapableBeanFactory#doCreateBean

其中doCreateBean 是在BeanFactory会调用到的函数

中都会调用

AbstractAutowireCapableBeanFactor#populateBean

然后调用

AbstractAutowireCapableBeanFactor#applyPropertyValues
在这个方法中会生成

BeanDefinitionValueResolver

然后会调用

BeanDefinitionValueResolver#resolveValueIfNecessary

然后会调用

BeanDefinitionValueResolver#doEvaluate

调用

AbstractBeanFactory#evaluateBeanDefinitionString

就是在这个地方实现SPEL的解析

回到prepareBeanFactory

增加对属性编辑器的支持

1
2
3
4
@Data
public class UserManager {
private Date dateValue;
}

然后我们尝试构造这个Bean

1
2
3
4
5
<bean id="userManager" class="com.test.UserManager">
<property name="dateValue">
<value>2013-01-01</value>
</property>
</bean>

事实上是会失败的

方法1
1
2
3
4
5
6
7
8
9
10
11
@Slf4j
public class DatePropertyEditor extends PropertyEditorSupport {
private static final DateTimeFormatter DATETIMEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

@Override
public void setAsText(String text) throws java.lang.IllegalArgumentException {
log.info("args {}", text);
Date date = Date.from(LocalDateTime.from(DATETIMEFORMATTER.parse(text)).atZone(ZoneId.systemDefault()).toInstant());
this.setValue(date);
}
}

然后在spring中进行注册

1
2
3
4
5
6
7
8
9
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entity key="java.util.Date">
<bean class=" com.example.demo.DatePropertyEditor"/>
</entity>
</map>
</property>
</bean>

这样的配置,当Spring在注入bean的属性时,一旦遇到了java.util.Date类型的属性会自动调用自定义的DatePropertyEditor

方法2
1
2
3
4
5
6
public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new DatePropertyEditor());
}
}
1
2
3
4
5
6
7
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.example.demo.DatePropertyEditorRegistrar"/>
</list>
</property>
</bean>
在什么时候触发的

AbstractAutowireCapableBeanFactory#doCreateBean

调用

AbstractAutowireCapableBeanFactory#createBeanInstance

调用

AbstractAutowireCapableBeanFactory#instantiateBean

调用

AbstractBeanFactory#initBeanWrapper

调用

AbstractBeanFactory#registerCustomEditors

调用

PropertyEditorRegistrar#registerCustomEditors

回到prepareBeanFactory

添加 ApplicationContextAwareProcessor 处理器 设置EnvironmentAware等的信息

ApplicationContextAwareProcessor#postProcessBeforeInitialization

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 Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}

AccessControlContext acc = null;

if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}

if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}

return bean;
}

ApplicationContextAwareProcessor#invokeAwareInterfaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}

回到prepareBeanFactory

设置了依赖功能可忽略的接口

*Aware 需要在Spring 做bean 依赖注入的时候忽略他们。因为他们不是普通的Bean,只是要实现和FactoryBean一样只是为了实现特定目的的Bean,就不要生成Bean,放到singletonObjects 里面了

1
2
3
4
5
6
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

调用顺序

调用的顺序为

AbstractAutowireCapableBeanFactory#doCreateBean

调用

AbstractAutowireCapableBeanFactory#populateBean

调用

AbstractAutowireCapableBeanFactory#autowireByType

or

AbstractAutowireCapableBeanFactory#autowireByName

调用

AbstractAutowireCapableBeanFactory#unsatisfiedNonSimpleProperties

调用

AbstractAutowireCapableBeanFactory#isExcludedFromDependencyCheck

回到prepareBeanFactory

注册固定依赖的属性

1
2
3
4
5
6
7
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 自动装配的特殊规则
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

调用的顺序为

AbstractAutowireCapableBeanFactory#doCreateBean

调用

AbstractAutowireCapableBeanFactory#populateBean

调用

AbstractAutowireCapableBeanFactory#autowireByType

调用

DefaultListableBeanFactory#resolveDependency

调用

DefaultListableBeanFactory#doResolveDependency

调用

DefaultListableBeanFactory#findAutowireCandidates

回到prepareBeanFactory

增加AspectJ的支持

将相关环境变量及属性注册以单例模式组册

回到reflush

invokeBeanFactoryPostProcessors

For example

org.springframework.beans.factory.config#PropertyOverrideConfigurer

这个类的作用是

回到reflush

registerBeanPostProcessors

回到reflush

-p09-】