Spring启动流程
总结
1.从run方法开始
spring的配置要从这个@SpringBootApplication这个注解里获取
2.进入run方法
3.进入SpringApplication方法
看看准备了什么样的环境
4.点进getSpringFactoriesInstance
5.点进loadFactoryNames
一直往下,点到
这一步是准备了很多类
6.回到第三步
进入getSpringFactoriesInstance看看是不是从缓存里取了
到这里环境就准备完了
7.回到第二步,进入run方法
8.
看看初始化后的环境是什么样子的
9.
10.进入refreshContext
往里面多走几步能找到refresh方法
11.点进prepareRefresh
12.回到10
13.点进prepareBeanFactory
14.回到12
15.进入finishBeanFactoryInitialization
16.进入preInstantiateSingletons
17.进入getBean,往下啊进
18.进入createBean
19.进入doCreateBean
自己写一个包装类
package com.example.studysource.test;
import java.lang.reflect.Field;
/**
* @author SJ
* @date 2021/4/11
*/
//对象包装类
public class ObjWrapper {
//持有一个对象
private Object object;
public Object getObject() {
return object;
}
//对外暴露两个方法
public void setObject(Object object) {
this.object = object;
}
public void setProp(String key,String value)throws Exception{
//拿到名字为key的私有字段 拿公有字段是getField
Field key1 = object.getClass().getDeclaredField(key);
//暴力注入
key1.setAccessible(true);
key1.set(object,value);
}
public static void main(String[] args) throws Exception{
User user = new User();
ObjWrapper objWrapper = new ObjWrapper();
objWrapper.setObject(user);
objWrapper.setProp("username","zhangsan");
System.out.println(objWrapper.getObject());
}
}
20.进入createBeanInstance
21.进入instantiateBean
22.进入instantiate
23.进入instantiateClass
24.回到14
完成Bean工厂初始化
25.回到9
完成refreshContext
控制台日志报错
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
是因为我们自动装配了mybatis,但没有配数据源,配一下就行。