Spring Boot 加载过程(自动配置及web服务)

简介: Spring Boot 加载过程(自动配置及web服务)

Spring Boot 加载过程(自动配置及web服务)

运行环境

IntelliJ IDEA 2019.2 (Community Edition)

Java 1.8.0_131

Maven apache-maven-3.5.4

Spring Boot  spring-boot-2.2.14.BUILD-SNAPSHOT

引入Spring Boot 依赖

pom.xml

<!-- 第一种方式 -->

<parent>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-parent</artifactId>

   <version>2.2.14.BUILD-SNAPSHOT</version>

</parent>

<!-- 第二种方式 -->

<dependencyManagement>

   <dependencies>

       <dependency>

           <!-- Import dependency management from Spring Boot -->

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-dependencies</artifactId>

           <version>2.2.14.BUILD-SNAPSHOT</version>

           <type>pom</type>

           <scope>import</scope>

       </dependency>

   </dependencies>

</dependencyManagement>

项目入口

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

publicclassTestApplication {

   publicstaticvoidmain(String[] args) {

       SpringApplication.run(TestApplication.class, args);

   }

}

@SpringBootApplication

@SpringBootApplication的源码,可以看到里面组合了三个注解:@ComponentScan,@SpringBootConfiguration,@EnableAutoConfiguration

@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@interfaceSpringBootApplication {

// ...

}

@ComponentScan

/**may be specified to define specific packages to scan. If specific

* packages are not defined, scanning will occur from the package of the

* class that declares this annotation.

可以指定来定义要扫描的特定包。如果未定义特定的包,则将从声明此注释的类的包中进行扫描。

*/

public@interfaceComponentScan {

//...

}

@SpringBootConfiguration

/**

* Indicates that a class provides Spring Boot application

* {@link Configuration @Configuration}. Can be used as an alternative to the Spring's

* standard {@code @Configuration} annotation so that configuration can be found

* automatically (for example in tests).

指示类提供Spring引导应用程序。可以作为Spring的标准{@code@Configuration}注释的替代,以便可以找到自动配置(例如在测试中)。

*/

@Configuration

public@interfaceSpringBootConfiguration {

//...

}

@EnableAutoConfiguration

@Import(AutoConfigurationImportSelector.class)

public@interfaceEnableAutoConfiguration {

//...

}

@EnableAutoConfiguration是springboot实现自动化配置的核心注解,通过这个注解把spring应用所需的bean注入容器中。@EnableAutoConfiguration源码通过@Import注入了一个ImportSelector的实现类 AutoConfigurationImportSelector,这个ImportSelector最终实现动态加载。 AutoConfigurationImportSelector完成动态加载过程如下:

org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process

org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getAutoConfigurationEntry

org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getCandidateConfigurations

org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames

publicfinalclassSpringFactoriesLoader {

   publicstaticfinalStringFACTORIES_RESOURCE_LOCATION="META-INF/spring.factories";

   privatestaticMap<String, List<String>>loadSpringFactories(@NullableClassLoaderclassLoader) {

       MultiValueMap<String, String>result=cache.get(classLoader);

       if (result!=null) {

           returnresult;

       }

       try {

           Enumeration<URL>urls= (classLoader!=null?

                   classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :

                   ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));

           result=newLinkedMultiValueMap<>();

           while (urls.hasMoreElements()) {

               URLurl=urls.nextElement();

               UrlResourceresource=newUrlResource(url);

               Propertiesproperties=PropertiesLoaderUtils.loadProperties(resource);

               for (Map.Entry<?, ?>entry : properties.entrySet()) {

                   StringfactoryTypeName= ((String) entry.getKey()).trim();

                   for (StringfactoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {

                       result.add(factoryTypeName, factoryImplementationName.trim());

                   }

               }

           }

           cache.put(classLoader, result);

           returnresult;

       }

       catch (IOExceptionex) {

           thrownewIllegalArgumentException("Unable to load factories from location ["+

                   FACTORIES_RESOURCE_LOCATION+"]", ex);

       }

   }

}

// 在classpath下所有的META-INF/spring.factories文件中查找org.springframework.boot.autoconfigure.EnableAutoConfiguration的值,并将其封装到一个List中返回,并将其加载到Spring 容器中。

ServletWebServerFactory  加载过程

首先在META-INF/spring.factories文件中可以找到 org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration类,Spring会在项目启动的时候,将其加载到Spring容器中。

@Configuration(proxyBeanMethods=false)

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)

@ConditionalOnClass(ServletRequest.class)

@ConditionalOnWebApplication(type=Type.SERVLET)

@EnableConfigurationProperties(ServerProperties.class)

@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,

       ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,

       ServletWebServerFactoryConfiguration.EmbeddedJetty.class,

       ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })

publicclassServletWebServerFactoryAutoConfiguration {

}

ServletWebServerFactoryAutoConfiguration类通过Import的方式将EmbeddedTomcat加载到容器中。

@Configuration(proxyBeanMethods=false)

classServletWebServerFactoryConfiguration {

   @Configuration(proxyBeanMethods=false)

    //根据条件进行加载 tomcatServletWebServerFactory

   @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })

   @ConditionalOnMissingBean(value=ServletWebServerFactory.class, search=SearchStrategy.CURRENT)

   staticclassEmbeddedTomcat {

       @Bean

       TomcatServletWebServerFactorytomcatServletWebServerFactory(

               ObjectProvider<TomcatConnectorCustomizer>connectorCustomizers,

               ObjectProvider<TomcatContextCustomizer>contextCustomizers,

               ObjectProvider<TomcatProtocolHandlerCustomizer<?>>protocolHandlerCustomizers) {

                   TomcatServletWebServerFactoryfactory=newTomcatServletWebServerFactory();

                   factory.getTomcatConnectorCustomizers()

                           .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList()));

                   factory.getTomcatContextCustomizers()

                           .addAll(contextCustomizers.orderedStream().collect(Collectors.toList()));

                   factory.getTomcatProtocolHandlerCustomizers()

                           .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));

                   returnfactory;

       }

   }

}

项目启动需要初始化SpringApplication类。构造方法会先进行环境类型的判断

org.springframework.boot.SpringApplication#SpringApplication(org.springframework.core.io.ResourceLoader, java.lang.Class<?>...)

@SuppressWarnings({ "unchecked", "rawtypes" })

publicSpringApplication(ResourceLoaderresourceLoader, Class<?>... primarySources) {

   this.resourceLoader=resourceLoader;

   Assert.notNull(primarySources, "PrimarySources must not be null");

   this.primarySources=newLinkedHashSet<>(Arrays.asList(primarySources));

   // 判断环境类型

   this.webApplicationType=WebApplicationType.deduceFromClasspath();

   setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

   this.mainApplicationClass=deduceMainApplicationClass();

}

#在通过以下调用过程最终通过createWebServer创建Web服务

org.springframework.boot.SpringApplication#refreshContext

org.springframework.boot.SpringApplication#refresh

org.springframework.context.support.AbstractApplicationContext#refresh

org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh

org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServer

privatevoidcreateWebServer() {

   WebServerwebServer=this.webServer;

   ServletContextservletContext=getServletContext();

   if (webServer==null&&servletContext==null) {

       // 获取 web 容器

       ServletWebServerFactoryfactory=getWebServerFactory();

       this.webServer=factory.getWebServer(getSelfInitializer());

   }

   elseif (servletContext!=null) {

       try {

           getSelfInitializer().onStartup(servletContext);

       }

       catch (ServletExceptionex) {

           thrownewApplicationContextException("Cannot initialize servlet context", ex);

       }

   }

   initPropertySources();

}


相关文章
|
4月前
|
算法 Java Go
【GoGin】(1)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
gin 框架中采用的路优酷是基于httprouter做的是一个高性能的 HTTP 请求路由器,适用于 Go 语言。它的设计目标是提供高效的路由匹配和低内存占用,特别适合需要高性能和简单路由的应用场景。
429 4
|
4月前
|
JavaScript Java 关系型数据库
基于springboot的美食城服务管理系统
本系统基于Spring Boot、Java、Vue和MySQL技术,构建集消费者服务、商家管理与后台监管于一体的美食城综合管理平台,提升运营效率与用户体验。
|
4月前
|
缓存 安全 Java
《深入理解Spring》过滤器(Filter)——Web请求的第一道防线
Servlet过滤器是Java Web核心组件,可在请求进入容器时进行预处理与响应后处理,适用于日志、认证、安全、跨域等全局性功能,具有比Spring拦截器更早的执行时机和更广的覆盖范围。
|
5月前
|
存储 安全 Java
如何在 Spring Web 应用程序中使用 @SessionScope 和 @RequestScope
Spring框架中的`@SessionScope`和`@RequestScope`注解用于管理Web应用中的状态。`@SessionScope`绑定HTTP会话生命周期,适用于用户特定数据,如购物车;`@RequestScope`限定于单个请求,适合无状态、线程安全的操作,如日志记录。合理选择作用域能提升应用性能与可维护性。
243 1
|
7月前
|
存储 Linux Apache
在CentOS上配置SVN至Web目录的自动同步
通过上述配置,每次当SVN仓库中提交新的更改时,`post-commit`钩子将被触发,SVN仓库的内容会自动同步到指定的Web目录,从而实现代码的连续部署。
224 16
|
6月前
|
存储 NoSQL Java
探索Spring Boot的函数式Web应用开发
通过这种方式,开发者能以声明式和函数式的编程习惯,构建高效、易测试、并发友好的Web应用,同时也能以较小的学习曲线迅速上手,因为这些概念与Spring Framework其他部分保持一致性。在设计和编码过程中,保持代码的简洁性和高内聚性,有助于维持项目的可管理性,也便于其他开发者阅读和理解。
213 0
|
7月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
524 0
|
7月前
|
Prometheus 监控 Cloud Native
Docker 部署 Prometheus 和 Grafana 监控 Spring Boot 服务
Docker 部署 Prometheus 和 Grafana 监控 Spring Boot 服务实现步骤
700 0
|
11月前
|
人工智能 自然语言处理 Java
对话即服务:Spring Boot整合MCP让你的CRUD系统秒变AI助手
本文介绍了如何通过Model Context Protocol (MCP) 协议将传统Spring Boot服务改造为支持AI交互的智能系统。MCP作为“万能适配器”,让AI以统一方式与多种服务和数据源交互,降低开发复杂度。文章以图书管理服务为例,详细说明了引入依赖、配置MCP服务器、改造服务方法(注解方式或函数Bean方式)及接口测试的全流程。最终实现用户通过自然语言查询数据库的功能,展示了MCP在简化AI集成、提升系统易用性方面的价值。未来,“对话即服务”有望成为主流开发范式。
7994 7