SpringBoot应该是每个Java程序猿都会使用的基础框架了,对于SpringBoot的核心内容自动装配原理的掌握就显得非常重要了。
![](https://img-blog.csdnimg.cn/img_convert/8a09719f62051ec253c97cf209d12e5e.png)
自动装配原理分析
1 理论介绍
SpringBoot通过自动装配实现了第三方框架系统对象的注入。这种实现机制和我们前面介绍的SPI(服务扩展机制)很相似。
![](https://img-blog.csdnimg.cn/img_convert/ebb30056b3aa4862f90c0af8d9834819.png)
2 源码分析
2.1 Spring的IoC
SpringBoot的本质是SpringFramework【IoC,AOP】的再次封装的上层应用框架。
![](https://img-blog.csdnimg.cn/img_convert/6682e90cd8fde654f7fe491db793fa46.png)
2.2 run方法
我们启动一个SpringBoot项目,本质上就是执行了启动类中的主方法,然后调用执行了run方法,那么run方法到底做了什么操作呢?我们可以先来分析下:
@SpringBootApplication
@MapperScan("com.bobo.mapper")
public class SpringBootVipDemoApplication {
public static void main(String[] args) {
// 基于配置文件的方式
ApplicationContext ac1 = new ClassPathXmlApplicationContext("");
// 基于Java配置类的方式
ApplicationContext ac2 = new AnnotationConfigApplicationContext(SpringBootVipDemoApplication.class);
// run 方法的返回对象是 ConfigurableApplicationContext 对象
ConfigurableApplicationContext ac3 = SpringApplication.run(SpringBootVipDemoApplication.class, args);
}
}
ConfigurableApplicationContext这个对象其实是 ApplicationContext接口的一个子接口
![](https://img-blog.csdnimg.cn/img_convert/f226cb32c8a34e094770b0cb86622f1a.png)
那么上面的代码可以调整为
@SpringBootApplication
@MapperScan("com.bobo.mapper")
public class SpringBootVipDemoApplication {
public static void main(String[] args) {
// 基于配置文件的方式
ApplicationContext ac1 = new ClassPathXmlApplicationContext("");
// 基于Java配置类的方式
ApplicationContext ac2 = new AnnotationConfigApplicationContext(SpringBootVipDemoApplication.class);
// run 方法执行完成后返回的是一个 ApplicationContext 对象
// 到这儿我们是不是可以猜测 run 方法的执行 其实就是Spring的初始化操作[IoC]
ApplicationContext ac3 = SpringApplication.run(SpringBootVipDemoApplication.class, args);
}
}