Spring Boot 启动流程及其原理

2022年6月17日 403点热度 0条评论

Spring Boot 启动流程及其原理

一 springboot启动原理及相关流程概览

springboot是基于spring的新型的轻量级框架,最厉害的地方当属自动配置。那我们就可以根据启动流程和相关原理来看看,如何实现传奇的自动配置。

img

1.从配置文件加载子类-----SPI机制,减少耦合,增加可配置扩展

2.IOC容器的生成--IOC

3.加载监听机制

4.类加载机制

二 springboot的启动类入口

用过springboot的技术人员很显而易见的两者之间的差别就是视觉上很直观的:springboot有自己独立的启动类(独立程序)

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
  }
}

从上面代码可以看出,Annotation定义(@SpringBootApplication)和类定义(SpringApplication.run)最为耀眼,所以要揭开SpringBoot的神秘面纱,我们要从这两位开始就可以了。

三 单单是SpringBootApplication接口用到了这些注解

@Target(ElementType.TYPE) // 注解的适用范围,其中TYPE用于描述类、接口(包括包注解类型)或enum声明
@Retention(RetentionPolicy.RUNTIME) // 注解的生命周期,保留到class文件中(三个生命周期)
@Documented // 表明这个注解应该被javadoc记录
@Inherited // 子类可以继承该注解
@SpringBootConfiguration // 继承了Configuration,表示当前是注解类
@EnableAutoConfiguration // 开启springboot的注解功能,springboot的四大神器之一,其借助@import的帮助
@ComponentScan(excludeFilters = { // 扫描路径设置(具体使用待确认)
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

public @interface SpringBootApplication {
	...
}  

img

在其中比较重要的有三个注解,分别是:

1)@SpringBootConfiguration // 继承了Configuration,表示当前是注解类

2)@EnableAutoConfiguration // 开启springboot的注解功能,springboot的四大神器之一,其借助@import的帮助

3)@ComponentScan(excludeFilters = { // 扫描路径设置(具体使用待确认)

接下来对三个注解一一详解,增加对springbootApplication的理解:

###  1)@Configuration注解

按照原来xml配置文件的形式,在springboot中我们大多用配置类来解决配置问题

  • 配置bean方式的不同:

a)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>

b)java configuration的配置形式配置bean

@Configuration
public class MockConfiguration{
    //bean定义
}
  • 注入bean方式的不同:

a)xml配置文件的形式注入bean

<bean id="mockService" class="..MockServiceImpl">
	
  ...

</bean>

b)java configuration的配置形式注入bean

@Configuration
public class MockConfiguration{
    @Bean
    public MockService mockService(){
        return new MockServiceImpl();
    }
}

任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,方法名将默认成该bean定义的id。

  • 表达bean之间依赖关系的不同:

a)xml配置文件的形式表达依赖关系

<bean id="mockService" class="..MockServiceImpl">

  <propery name ="dependencyService" ref="dependencyService" />

</bean>

<bean id="dependencyService" class="DependencyServiceImpl"></bean>4

b)java configuration配置的形式表达依赖关系(重点)

如果一个bean A的定义依赖其他bean B,则直接调用对应的JavaConfig类中依赖bean B的创建方法就可以了。

@Configuration
public class MockConfiguration{
  @Bean
  public MockService mockService(){
      return new MockServiceImpl(dependencyService());
  }
  @Bean
  public DependencyService dependencyService(){
      return new DependencyServiceImpl();
  }
}

### 2)@ComponentScan注解

作用:a)对应xml配置中的元素;

b)(重点)ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义;

c) 将这些bean定义加载到IoC容器中.

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。

注:所以SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages

  1. @EnableAutoConfiguration 此注解顾名思义是可以自动配置,所以应该是springboot中最为重要的注解。

​ 在spring框架中就提供了各种以@Enable开头的注解,例如: @EnableScheduling、@EnableCaching、@EnableMBeanExport等; @EnableAutoConfiguration的理念和做事方式其实一脉相承简单概括一下就是,借助@Import的支持,收集和注册特定场景相关的bean定义。

  • @EnableScheduling是通过@Import将Spring调度框架相关的bean定义都加载到IoC容器【定时任务、时间调度任务】
  • @EnableMBeanExport是通过@Import将JMX相关的bean定义加载到IoC容器【监控JVM运行时状态】
  • @EnableAutoConfiguration也是借助@Import的帮助,将所有符合自动配置条件的bean定义加载到IoC容器。
  • @EnableAutoConfiguration作为一个复合Annotation,其自身定义关键信息如下:
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage // 【重点注解】
@Import(AutoConfigurationImportSelector.class) // 【重点注解】
public @interface EnableAutoConfiguration {

	...

}

其中最重要的两个注解已经标注:1、@AutoConfigurationPackage【重点注解】2、@Import(AutoConfigurationImportSelector.class)【重点注解】

当然还有其中比较重要的一个类就是:EnableAutoConfigurationImportSelector.class

AutoConfigurationPackage注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

通过@Import(AutoConfigurationPackages.Registrar.class)

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
  @Override
  public void registerBeanDefinitions(AnnotationMetadata metadata,
    BeanDefinitionRegistry registry) {
    register(registry, new PackageImport(metadata).getPackageName());
  }
  ……
 }

它其实是注册了一个Bean的定义;

new PackageImport(metadata).getPackageName(),它其实返回了当前主程序类的同级以及子级的包组件(重点);

(重点)那这总体就是注册当前主程序类的同级以及子级的包中的符合条件的Bean的定义?

img

以上图为例,DemoApplication是和demo包同级,但是demo2这个类是DemoApplication的父级,和example包同级

也就是说,DemoApplication启动加载的Bean中,并不会加载demo2,这也就是为什么,我们要把DemoApplication放在项目的最高级中。

Import(AutoConfigurationImportSelector.class)注解

img

(重点)可以从图中看出 AutoConfigurationImportSelector 实现了 DeferredImportSelector 从 ImportSelector继承的方法:selectImports。

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
  if (!isEnabled(annotationMetadata)) {
   
    return NO_IMPORTS;
		
  }
  
  AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
  
  AnnotationAttributes attributes = getAttributes(annotationMetadata);
  
  List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
  
  configurations = removeDuplicates(configurations);
  
  Set<String> exclusions = getExclusions(annotationMetadata, attributes);
  
  checkExcludedClasses(configurations, exclusions);
  
  configurations.removeAll(exclusions);
  
  configurations = filter(configurations, autoConfigurationMetadata);
  
  fireAutoConfigurationImportEvents(configurations, exclusions);
  
  return StringUtils.toStringArray(configurations);
}


  

List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes);这行其实是去加载各个组件jar下的 public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"外部文件。

该方法在springboot启动流程——bean实例化前被执行,返回要实例化的类信息列表;

如果获取到类信息,spring可以通过类加载器将类加载到jvm中,现在我们已经通过spring-boot的starter依赖方式依赖了我们需要的组件,那么这些组件的类信息在select方法中就可以被获取到。

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {

 List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

 Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");

 return configurations;

 }

其返回一个自动配置类的类名列表,方法调用了loadFactoryNames方法,查看该方法

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {

 String factoryClassName = factoryClass.getName();

 return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());

 }

自动配置器会跟根据传入的factoryClass.getName()到项目系统路径下所有的spring.factories文件中找到相应的key,从而加载里面的类。

这个外部文件,有很多自动配置的类。如下:

img

(重点)其中,最关键的要属@Import(AutoConfigurationImportSelector.class),借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件(spring.factories)的bean定义(如Java Config@Configuration配置)都加载到当前SpringBoot创建并使用的IoC容器。就像一只“八爪鱼”一样。

img

自动配置幕后英雄:SpringFactoriesLoader详解

借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自动配置功效才得以大功告成!

SpringFactoriesLoader属于Spring框架私有的一种扩展方案,其主要功能就是从指定的配置文件META-INF/spring.factories加载配置,加载工厂类

SpringFactoriesLoader为Spring工厂加载器,该对象提供了loadFactoryNames方法,入参为factoryClass和classLoader即需要传入工厂类名称和对应的类加载器,方法会根据指定的classLoader,加载该类加器搜索路径下的指定文件,即spring.factories文件;

传入的工厂类为接口,而文件中对应的类则是接口的实现类,或最终作为实现类。

public abstract class SpringFactoriesLoader {
//...
  public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
    ...
  }

  public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    ....
  }
}

配合@EnableAutoConfiguration使用的话,它更多是提供一种配置查找的功能支持,即根据@EnableAutoConfiguration的完整类名org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,获取对应的一组@Configuration类

img

上图就是从SpringBoot的autoconfigure依赖包中的META-INF/spring.factories配置文件中摘录的一段内容,可以很好地说明问题。

(重点)所以,@EnableAutoConfiguration自动配置的魔法其实就变成了:

从classpath中搜寻所有的META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的配置项通过反射(Java Refletion)实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器。

img

四 springboot启动流程概览图

img

五 深入探索SpringApplication执行流程

img

public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered

EventPublishingRunListener实现了SpringApplicationRunListener接口;

实现了方法,下面是部分方法源码

		@Override
    public void starting() {
        this.initialMulticaster.multicastEvent(
                new ApplicationStartingEvent(this.application, this.args));
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
    
        this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
    
                this.application, this.args, environment));
    
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
    
        this.initialMulticaster.multicastEvent(new ApplicationContextInitializedEvent(
    
                this.application, this.args, context));
    
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

     .....................

简单了解下Bean的生命周期

img

一个Bean的构造函数初始化时是最先执行的,这个时候,bean属性还没有被注入;

@PostConstruct注解的方法优先于InitializingBean的afterPropertiesSet执行,这时Bean的属性竟然被注入了;

spring很多组件的初始化都放在afterPropertiesSet做,想和spring一起启动,可以放在这里启动;

spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用;

实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点;但是init-method方式消除了对spring的依赖;

如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。

Bean在实例化的过程中:

Constructor > @PostConstruct > InitializingBean > init-method

BeanFactory 和ApplicationContext的区别 BeanFactory和ApplicationContext都是接口,并且ApplicationContext间接继承了BeanFactory。

BeanFactory是Spring中最底层的接口,提供了最简单的容器的功能,只提供了实例化对象和获取对象的功能,而ApplicationContext是Spring的一个更高级的容器,提供了更多的有用的功能。

ApplicationContext提供的额外的功能:获取Bean的详细信息(如定义、类型)、国际化的功能、统一加载资源的功能、强大的事件机制、对Web应用的支持等等。

加载方式的区别:BeanFactory采用的是延迟加载的形式来注入Bean;ApplicationContext则相反的,它是在Ioc启动时就一次性创建所有的Bean,好处是可以马上发现Spring配置文件中的错误,坏处是造成浪费。

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
        MessageSource, ApplicationEventPublisher, ResourcePatternResolver

SpringMVC处理请求的流程

1、用户发送请求至前端控制器DispatcherServlet

2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。

3、处理器映射器根据请求url找到具体的处理器,生成处理器对象Handler及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。

4、DispatcherServlet通过HandlerAdapter(让Handler实现更加灵活)处理器适配器调用处理器

5、执行处理器(Controller,也叫后端控制器)。

6、Controller执行完成返回ModelAndView(连接业务逻辑层和展示层的桥梁,持有一个ModelMap对象和一个View对象)。

7、HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet

8、DispatcherServlet将ModelAndView传给ViewReslover视图解析器

9、ViewReslover解析后返回具体View

10、DispatcherServlet对View进行渲染视图(将ModelMap模型数据填充至视图中)。

11、DispatcherServlet响应用户

harry

这个人很懒,什么都没留下

文章评论