springBoot以jar包的启动原理
1.SpringBoot简介
1.1什么是springBoot
Spring Boot 是所有基于 Spring 开发的项目的起点,是Spring对轻量级框架的延伸。Spring Boot 的设计是为了让你从繁琐的配置文件解放出来。简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,spring boot整合了所有的框架(自动装配);它内置Tomcat、Jetty和Undertow三种web容器。
2.springBoot的启动方式
2.1 SpringBoot的web容器
在以下代码中,我们看到SpringBoot内置Tomcat、Jetty和Undertow,它是通过pom.xml中的依赖从而得知以哪一个web容器启动(@ConditionalOnClass是@Conditional的衍生注解,从而得知@ConditionalOnClass里的class存在就能注入到IOC容器中,激活配置)。
@Configuration
@EnableConfigurationProperties(ServerProperties.class)
public class EmbeddedWebServerFactoryCustomizerAutoConfiguration {
@ConditionalOnClass({ Tomcat.class, UpgradeProtocol.class })
public static class TomcatWebServerFactoryCustomizerConfiguration {
@Bean
public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new TomcatWebServerFactoryCustomizer(environment, serverProperties);
}
}
/**
* Nested configuration if Jetty is being used.
*/
@Configuration
@ConditionalOnClass({ Server.class, Loader.class, WebAppContext.class })
public static class JettyWebServerFactoryCustomizerConfiguration {
@Bean
public JettyWebServerFactoryCustomizer jettyWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new JettyWebServerFactoryCustomizer(environment, serverProperties);
}
}
/**
* Nested configuration if Undertow is being used.
*/
@Configuration
@ConditionalOnClass({ Undertow.class, SslClientAuthMode.class })
public static class UndertowWebServerFactoryCustomizerConfiguration {
@Bean
public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new UndertowWebServerFactoryCustomizer(environment, serverProperties);
}
}
}
2.2 SpringBoot 的启动流程
在SpringBoot中我们怎么进入我们需要查看的源码?在SpringBoot的启动类中有@SpringBootApplication注解,这个是进入自动装配源码,不是我们需要的(如果有时间的话我会讲解自动装配的原理),main方法则是我们的启动方式源码。废话不多说,上图。
2.2.1 保存住主置类
2.2.2 运行SpringbootApplication的run方法
2.2.3 run方法中的refreshContext方法
在上图中有个refreshContext(context)方法很重要,通过该方法进入IOC的核心方法refresh(),然后进入ServletWebServerApplicationContext类的onRefresh()方法,在这里createWebServer()方法中帮我们创建web容器。
2.2.4 创建web容器
这里我们以Tomcat为例,在这里SpringBoot为我们创建容器,赋值,最后激活容器