springboot启动流程及原理

springboot启动入口类

@SpringBootApplication
public class SpringBootWebApplication {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringBootWebApplication.class);
        application.run(args);
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}

以上代码很容易看出哪些是关键,当然是@SpringBootApplication和application.run()分别是springboot加载配置和启动,下面详细说明这两块。
其中@Configuration(@SpringBootConfiguration中其实用的也是@Configuration);@EnableAutoConfiguration;@ComponentScan三个是最重要的注解,@SpringBootApplication整合了三个注解使用者写起来看起来都比较简洁。

@Configuration
它就是JavaConfig形式的Spring Ioc容器的配置类使用的那个@Configuration,这里的启动类标注了@Configuration之后,本身其实也是一个IoC容器的配置类。如下案例说明xml和注解实现bean的定义

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
       default-lazy-init="true">
       <!--bean定义-->
</beans>

@EnableAutoConfiguration

@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@EnableAutoConfiguration简单的说它的作用就是借助@Import的支持,收集和注册特定场景相关的bean定义。其中,最关键的要属@Import(EnableAutoConfigurationImportSelector.class),借助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持很智能的自动配置:
在这里插入图片描述
SpringFactoriesLoader其主要功能就是从指定的配置文件META-INF/spring.factories加载配置。将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射(Java Refletion)实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器

启动流程RUN概述
SpringBoot的启动逻辑在SpringApplication这个类中,通过构造一个SpringApplication并调用run方法启动SpringBoot应用程序。SpringBoot启动后的主要流程:

  1. 设置webApplicationType(web应用类型)
    webApplicationType是启动流程中一个比较重要的属性,SpringBoot根据它的类型来创建Environment对象和应用上下文对象(ApplicationContext)

  2. 准备应用上下文环境(Environment)
    根据上一步推断的webApplicationType创建不同类型的Environment,并且将用户的profile文件读取到Environment中

  3. 读取profile

  4. 创建并配置应用上下文对象(ApplicationContext)
    根据webApplicationType创建不同实现的ApplicationContext

  5. 刷新应用上下文对象(refresh)
    AbstractApplicationContext抽象类定义了上下文对象初始化核心流程,SpringBoot以BeanFactoryPostProcessor的方式实现包扫描、自动配置,将Bean预先加载成BeanDefinition后并实例化

  6. 后续处理
    发布应用已启动事件并且调用容器中的Runner

发布了24 篇原创文章 · 获赞 15 · 访问量 1160

猜你喜欢

转载自blog.csdn.net/shenhuxi10000/article/details/103724274
今日推荐