本期狮码 | 王猛
简介:从事程序猿差不多9年啦,喜欢研究代码、K歌、打台球。
大家一直用spring boot,使用起来最大的优点就是当做web 服务时不用依赖tomcat就能快速启动起来、省去一堆的xml配置,提供了便捷的注解。那么spring boot都做了哪些呢?带着好奇心我们来看一下吧。
一、简介
官网:https://spring.io/projects/spring-boot
很容易创建独立的、生产级的基于Spring的应用程序(俗称咱们常用的java接口服务)
特点:
创建独立的Spring应用程序
直接嵌入Tomcat、Jetty或底层(不需要部署WAR文件)
提供 'starter' 的简化配置
自动的配置Spring程序和三方库
提供生产就绪的特性,例如度量、健康检查和外部化配置
无代码和无xml配置的环境启动
二、启动原理
1、如果是web工程,我们依赖了spring -boot-starter-web 则自带嵌套tomcat
参考:
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/getting-started.html#getting-started-first-application-auto-configuration
2、关于打包
创建可执行jar (sometimes called “fat jars”) ,我们需要依赖spring-boot-maven-plugin插件,打包时就会将依赖的jar都放入可执行jar的“BOOT-INF/lib”目录。
注意:若工程未指定parent是spring-boot-starter-parent,则需要spring-boot-maven-plugin 设置executions.execution.goals.goal=repackage,将依赖jar打包到执行jar内。
参考:
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/getting-started.html#getting-started-first-application-executable-jar
3、关于类加载
java没有提供执行嵌套jar的规范(可执行jar内部包含依赖jar),spring boot提供了3个 Launcher(JarLauncher, WarLauncher, and PropertiesLauncher)解决了此问题。
pom中packaging是jar则使用的JarLauncher,在打包后的可执行jar里文件META INF/MANIFEST.MF能看到
参考:
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/appendix-executable-jar-format.html#executable-jar
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/appendix-executable-jar-format.html#executable-jar-launching
4、启动spring jar 执行“java jar xxx.jar”
spring jar的实际执行类MainClass是JarLauncher,见*.jar//METAINF/MANIFEST.MF文件
JarLauncher调用Launcher.launch
参考:
https://docs.spring.io/spring-boot/docs/2.3.0.RELEASE/reference/html/appendix-executable-jar-format.html#executable-jar-launchin
5、main方法执行:
SpringApplication.run() >> new SpringApplication(primarySources).run(args)
初始化SpringApplication
SpringApplication.run
6、到这里我们的web服务就可以正常访问啦。
三、结语
看到这里相信大家对spring boot的启动过程也算是有所入门了(大牛除外),有写的不好的地方欢迎大牛们指点。