SpringBoot的启动配置原理

简介: 介绍SpringBoot的启动配置原理

一、启动流程

  1. 创建SpringApplication对象
publicclassSpringApplication {
publicSpringApplication(Class... primarySources) {
this((ResourceLoader)null, primarySources);
    }
publicSpringApplication(ResourceLoaderresourceLoader, Class... primarySources) {
this.sources=newLinkedHashSet();
this.bannerMode=Mode.CONSOLE;
this.logStartupInfo=true;
this.addCommandLineProperties=true;
this.addConversionService=true;
this.headless=true;
this.registerShutdownHook=true;
this.additionalProfiles=newHashSet();
this.isCustomEnvironment=false;
this.resourceLoader=resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 保存主配置类this.primarySources=newLinkedHashSet(Arrays.asList(primarySources));
// 判断当前是否一个web应用this.webApplicationType=WebApplicationType.deduceFromClasspath();                                                            
// 从类路径下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起来。this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 从类路径下找到META-INF/spring.factories配置的所有ApplicationListenerthis.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//从多个配置类中找到有main方法的主配置类this.mainApplicationClass=this.deduceMainApplicationClass();
    }
  1. 运行run方法
publicConfigurableApplicationContextrun(String... args) {
StopWatchstopWatch=newStopWatch();
stopWatch.start();
ConfigurableApplicationContextcontext=null;
Collection<SpringBootExceptionReporter>exceptionReporters=newArrayList();
this.configureHeadlessProperty();
// 获取SpringApplicationRunListener; 从类路径下META-INF/spring.factories获取SpringApplicationRunListenerslisteners=this.getRunListeners(args);
// 回调所有的获取SpringApplicationRunListener.starting()方法listeners.starting();
CollectionexceptionReporters;
try {
// 封装命令行参数ApplicationArgumentsapplicationArguments=newDefaultApplicationArguments(args);
// 准备环境ConfigurableEnvironmentenvironment=this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 创建环境完成后回调SpringApplicationRunListener.environmentPrepared();表示环境准备完成BannerprintedBanner=this.printBanner(environment);
// 创建ApplicationContext;决定创建web的IOC还是普通的IOCcontext=this.createApplicationContext();
exceptionReporters=this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, newClass[]{ConfigurableApplicationContext.class}, context);
// 准备上下文环境;将environment保存到IOC中,而且applyInitializers();// 而且applyInitializers():回调之前保存的所有ApplicationContextInitializer的initialize方法// 回调所有的SpringApplicationRunListener的contextPrepared();this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// prepareContext运行完成以后回调所有的SpringApplicationRunListener的contextLoaded();// 扫描容器;IOC容器初始化(如果是web应用还会创建嵌入的Tomcat);// 扫描,创建,加载所有组件的地方(配置类,组件,自动配置)this.refreshContext(context);
// 从IOC容器中获取所有的ApplicationRunner和CommandLineRunner进行回调// ApplicationRunner先回调,CommandLineRunner再回调this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
                (newStartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }
listeners.started(context);
this.callRunners(context, applicationArguments);
        } catch (Throwablevar10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
thrownewIllegalStateException(var10);
        }
try {
listeners.running(context);
// 整个SpringBoot应用启动完成以后返回启动的IOC容器returncontext;
        } catch (Throwablevar9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
thrownewIllegalStateException(var9);
        }
    }
  1. 事件监听机制
    需要配置在META-INF/spring.factories中的事件监听器。
    ApplicationContextInitializer
publicclassCustomApplicationContextInitializerimplementsApplicationContextInitializer<ConfigurableApplicationContext> {
@Overridepublicvoidinitialize(ConfigurableApplicationContextconfigurableApplicationContext) {
System.out.println("ApplicationContextInitializer.....initialize");
    }
}

SpringApplicationRunListener

publicclassCustomSrpingApplicationRunListenerimplementsSpringApplicationRunListener {
// 必须有的构造器publicCustomSrpingApplicationRunListener(SpringApplicationapplication,String[] args){
    }
@Overridepublicvoidstarting() {
System.out.println("SpringApplicationRunListener...starting....");
    }
@OverridepublicvoidenvironmentPrepared(ConfigurableEnvironmentenvironment) {
Objecto=environment.getSystemEnvironment().get("os.name");
System.out.println("SpringApplicationRunListener...environmentPrepared...."+o);
    }
@OverridepublicvoidcontextPrepared(ConfigurableApplicationContextcontext) {
System.out.println("SpringApplicationRunListener..contextPrepared");
    }
@OverridepublicvoidcontextLoaded(ConfigurableApplicationContextcontext) {
System.out.println("SpringApplicationRunListener..contextLoaded");
    }
@Overridepublicvoidstarted(ConfigurableApplicationContextcontext) {
System.out.println("SpringApplicationRunListener..started");
    }
@Overridepublicvoidrunning(ConfigurableApplicationContextcontext) {
System.out.println("SpringApplicationRunListener..running");
    }
@Overridepublicvoidfailed(ConfigurableApplicationContextcontext, Throwableexception) {
System.out.println("SpringApplicationRunListener..failed");
    }
}

配置(META-INF/spring.factories)

org.springframework.context.ApplicationContextInitializer=com.desperado.demo.CustomApplicationContextInitializerorg.springframework.boot.SpringApplicationRunListener=com.desperado.demo.CustomSrpingApplicationRunListener

只需要放在IOC容器中的监听器。

ApplicationRunner

@ComponentpublicclassCustomApplicationRunnerimplementsApplicationRunner {
@Overridepublicvoidrun(ApplicationArgumentsargs) {
System.out.println("ApplicationRunner ... run....");
    }
}

CommandLineRunner

@ComponentpublicclassCustomCommandLineRunnerimplementsCommandLineRunner {
@Overridepublicvoidrun(String... args) {
System.out.println("commandLineRunner ... run ...");
    }
}

二、自定义starter

  1. 要使用到的注解
    @Configuration 指定类是一个配置类
    @ConditionalOnXXX 在指定条件成立的情况下自动配置生效、
    @AutoConfigureAfter 在特定自动装配class之后(指定自动配置类的顺序)
    @AutoConfigureBefore 在特定自动装配class之前(指定自动配置类的顺序)
    @AutoConfigureOrder 指定顺序
    @Bean 给容器中添加组件
    @ConfigurationPropertie 结合相关xxxProperties类来绑定相关的配置。
    @EnableConfigurationProperties 让xxxProperties生效加入到容器中。


  1. 加载方式
    自动配置类要能加载,将需要启动就加载的自动配置类,配置在META-INF/spring.factories文件中。


  1. 启动器模式
    启动器只用来做依赖导入,专门写一个自动配置模块。启动器依赖自动配置,使用时只需要引入启动器(starter)。


  1. 启动器规则
    启动器就是个空jar文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他库。


命名规范:

- 推荐使用以下命名规范

- 官方命名空间

 - 前缀:spring-boot-starter-

 - 模式:spring-boot-starter-模块名 - 自定义命名空间

  - 后缀:-spring-boot-starter

 - 模式:模块名-spring-boot-starter


  1. 编写一个启动器模块
    1). 启动器模块
<?xmlversion="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.desperado.starter</groupId><artifactId>desperado-spring-boot-starter</artifactId><version>0.0.1-SNAPSHOT</version><!-- 启动器 --><dependencies><!-- 引入自动配置模块 --><dependency><groupId>com.desperado.starter</groupId><artifactId>desperado-spring-boot-starter-autoconfigurer</artifactId><version>0.0.1-SNAPSHOT</version></dependency></dependencies></project>

2). 自动配置模块

<?xmlversion="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.desperado.starter</groupId><artifactId>desperado-spring-boot-starter-autoconfigurer</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.5.RELEASE</version><relativePath/></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><!--  引入spring-boot-starter;所有starter的基本配置 --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>

3). 编写配置文件类

@ConfigurationProperties(prefix="desperado.custom")
publicclassCustomProperties {
privateStringprefix;
privateStringsuffix;
publicStringgetPrefix() {
returnprefix;
    }
publicvoidsetPrefix(Stringprefix) {
this.prefix=prefix;
    }
publicStringgetSuffix() {
returnsuffix;
    }
publicvoidsetSuffix(Stringsuffix) {
this.suffix=suffix;
    }
}

4). 进行配置文件的处理

publicclassCustomService {
CustomPropertiescustomProperties;
publicCustomPropertiesgetCustomProperties(){
returncustomProperties;
    }
publicvoidsetCustomProperties(CustomPropertiescustomProperties){
this.customProperties=customProperties;
    }
publicStringsayHello(Stringname){
returncustomProperties.getPrefix()+"-"+name+customProperties.getSuffix();
    }
}

5). 编写自动配置类

@ConditionalOnWebApplication@EnableConfigurationProperties(CustomProperties.class)
publicclassCustomServiceAutoConfiguration {
@AutowiredCustomPropertiescustomProperties;
@BeanpublicCustomServicecustomService(){
CustomServicecustomService=newCustomService();
customService.setCustomProperties(customProperties);
returncustomService;
    }
}
目录
打赏
0
0
0
0
78
分享
相关文章
|
11天前
|
SpringBoot自动装配的原理
在SpringBoot项目的启动引导类上都有一个注解@SpringBootApplication 这个注解是一个复合注解, 其中有三个注解构成 , 分别是 ● @SpringBootConfiguration : 是@Configuration的派生注解 , 标注当前类是一个SpringBoot的配置类 ● @ComponentScan : 开启组件扫描, 默认扫描的是当前启动引导了所在包以及子包 ● @EnableAutoConfiguration : 开启自动配置(自动配置核心注解) 2.在@EnableAutoConfiguration注解的内容使用@Import注解导入了一个AutoC
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
99 12
Spring Boot开箱即用可插拔实现过程演练与原理剖析
【11月更文挑战第20天】Spring Boot是一个基于Spring框架的项目,其设计目的是简化Spring应用的初始搭建以及开发过程。Spring Boot通过提供约定优于配置的理念,减少了大量的XML配置和手动设置,使得开发者能够更专注于业务逻辑的实现。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,为开发者提供一个全面的理解。
76 0
springboot自动配置原理
Spring Boot 自动配置原理:通过 `@EnableAutoConfiguration` 开启自动配置,扫描 `META-INF/spring.factories` 下的配置类,省去手动编写配置文件。使用 `@ConditionalXXX` 注解判断配置类是否生效,导入对应的 starter 后自动配置生效。通过 `@EnableConfigurationProperties` 加载配置属性,默认值与配置文件中的值结合使用。总结来说,Spring Boot 通过这些机制简化了开发配置流程,提升了开发效率。
93 17
springboot自动配置原理
Idea启动SpringBoot程序报错:Veb server failed to start. Port 8082 was already in use;端口冲突的原理与解决方案
本文解决了Idea启动SpringBoot程序报错:Veb server failed to start. Port 8082 was already in use的问题,并通过介绍端口的使用原理和操作系统的端口管理机制,可以更有效地解决端口冲突问题,并确保Web服务器能够顺利启动和运行。 只有锻炼思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
自动装配是现在面试中常考的一道面试题。本文基于最新的 SpringBoot 3.3.3 版本的源码来分析自动装配的原理,并在文未说明了SpringBoot2和SpringBoot3的自动装配源码中区别,以及面试回答的拿分核心话术。
最新版 | 深入剖析SpringBoot3源码——分析自动装配原理(面试常考)
Spring Boot 自动配置机制:从原理到自定义
Spring Boot 的自动配置机制通过 `spring.factories` 文件和 `@EnableAutoConfiguration` 注解,根据类路径中的依赖和条件注解自动配置所需的 Bean,大大简化了开发过程。本文深入探讨了自动配置的原理、条件化配置、自定义自动配置以及实际应用案例,帮助开发者更好地理解和利用这一强大特性。
265 14
|
5月前
|
SpringBoot自动装配的原理
在Spring Boot项目中,启动引导类通常使用`@SpringBootApplication`注解。该注解集成了`@SpringBootConfiguration`、`@ComponentScan`和`@EnableAutoConfiguration`三个注解,分别用于标记配置类、开启组件扫描和启用自动配置。
89 17
springboot自动配置原理
启动类@SpringbootApplication注解下,有三个关键注解 (1)@springbootConfiguration:表示启动类是一个自动配置类 (2)@CompontScan:扫描启动类所在包外的组件到容器中 (3)@EnableConfigutarion:最关键的一个注解,他拥有两个子注解,其中@AutoConfigurationpackageu会将启动类所在包下的所有组件到容器中,@Import会导入一个自动配置文件选择器,他会去加载META_INF目录下的spring.factories文件,这个文件中存放很大自动配置类的全类名,这些类会根据元注解的装配条件生效,生效
Java面试题:解释Spring Boot的优势及其自动配置原理
Java面试题:解释Spring Boot的优势及其自动配置原理
160 0

热门文章

最新文章