走进Spring Boot源码学习之路和浅谈入门
yuyutoo 2024-10-26 16:09 7 浏览 0 评论
Spring Boot浅聊入门
Spring Boot官网地址:https://spring.io/projects/spring-boot/
Spring Boot可以轻松创建独立的、基于Spring的产品级应用程序“直接运行”。
作为笔者见解,Spring Boot 不算是一个全新的框架,Spring Boot 底层还是大量依赖于Spring Framework,而Spring Framework很早以前版本就已提供基于注解、Java Config而不仅是XML配置编程;Spring Boot采用约定大于配置方式替代xml配置,是Spring Framework一个大升级版本,整合很多自动装配组件,让开发者开箱即用,接下来我们一起来聊聊Spring Boot三个重要的特性和starter开发简易剖析
Spring Boot源码编译
使用最新Releases版本v2.5.3
目前Spring boot和Spring Framework项目都是使用Gradle自动化构建工具,编译直接查看项目根目录下README.adoc文件即可,有时网络不好可以多次编译重试
零配置
Spring Web MVC简述
Spring Web Mvc官网地址** **https://docs.spring.io/spring-framework/docs/current/reference/html/web.html
Spring Web MVC是基于Servlet API的原始Web框架,从一开始就包含在Spring框架中。“Spring Web MVC”的正式名称来自其源模块的名称(Spring -webmvc),但它通常被称为“Spring MVC”
零配置实现
Spring Web MVC官网开篇最前面第一章第一小节也即是1.1 DispatcherServlet中就重点引用一下这六句代码实现原来我们Spring MVC 工程web.xml里面配置功能,仅通过下面这一小段代码就初始化了Spring根容器和Web子容器,这种方式也是官方推荐使用的
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
?
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
}
}
而我们非常熟悉的Spring Web Mvc工程web.xml配置示例注册和初始化DispatcherServlet:
<web-app>
?
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
?
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</context-param>
?
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
?
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
?
</web-app>
父子容器
个人猜测Spring Boot基于内嵌容器特性会渐渐淡化父子容器的概念,最终只是一个大容器
内嵌容器
概述
Spring Boot 内嵌像Tomcat、Jetty、Undertow等实现Servlet规范的容器,如果有研究过Tomcat这只三脚猫logo中间件(后续有时间我们再分享一下Tomcat源码和原理)也知道Tomcat也是一个用Java语言编写的强大中间件,在Spring Boot通过New Tomcat方式来配置和启动web容器。
Spring Framework源码编译
使用最新Release版本v5.2.16.RELEASE
同样找到项目根目录下README.md,从githubSpring Framework源码** wiki找到编译源码说明**
实现
根据Servlet从3.0版本之后的规范,所有实现Servlet规范的Web容器都会扫描jar包下面META-INF/services下的文件,在Spring Web子项目中利用Java 的SPI机制(SPI是一种扩展机制,很多框架底层都使用或甚至重新实现自己的SPI机制,比如像Spring和Dubbo都实现自己的SPI,以后我们再找时间来讨论,暂且到这里),在根目录下META-INF/services创建一个文件名javax.servlet.ServletContainerInitializer,文件内容是实现类的org.springframework.web.SpringServletContainerInitializer全类名
SpringServletContainerInitializer实现类针对通过@HandlesTypes感兴趣注解, 将所有实现WebApplicationInitializer的实现类放到一个Set集合中,然后再逐个调用其onStartup()方法,所以这里我们接上了1.1章节官网MyWebApplicationInitializer实现WebApplicationInitializer接口这一部分
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
?
List<WebApplicationInitializer> initializers = Collections.emptyList();
?
if (webAppInitializerClasses != null) {
initializers = new ArrayList<>(webAppInitializerClasses.size());
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
?
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
?
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
?
}
接下来我们再来看看Web容器如Tomcat是如何在Spring Boot中运行的,首先我们先得知道SpringBoot启动过程,我们知道Spring Boot 应用程序都是从SpringApplication.run开始的,而run方法则始于SpringApplication类,返回ApplicationContext接口的子接口ConfigurableApplicationContext,通过refreshContext方法调用Spring Framework最大名鼎鼎的refresh方法初始化Spring容器,而refresh方法中的onRefresh是留给子类扩展使用的,而也是在这里开始初始化Web容器的
找到其实现类ServletWebServerApplicationContext,在这里createWebServer开始创建WebServer,
这里会根据我们我们pom文件starter依赖来决定创建Tomcat、Undertow、Jetty,Undertow在并发下性能明显优化另外Tomcat和Jetty,建议优先使用Undertow,但这里由于大家对于Tomcat印象比较深刻,所以我们示例还是以Tomcat为主
Spring Boot内嵌容器默认为Tomcat,想要换成Undertow也是非常容易的,只需修改spring-boot-starter-web依赖,移除tomcat的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
添加undertow依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
server:
port: 8084
http2:
enabled: true
undertow:
io-threads: 16
worker-threads: 256
buffer-size: 1024
buffers-per-region: 1024
direct-buffers: true
至此,这里我们通过ServletWebServerFactory的实现类TomcatServletWebServerFactory的getWebServer方法找到new Tomcat的源码
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
connector.setThrowOnFailure(true);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
自动装配
@SpringBootApplication注解
我们知道所有运用Spring Boot应用程序在根目录的主类上都标有一个@SpringBootApplication的注解,这个就是SpringBoot自动装配实现的入口,我们接下来一步步的来分析,首先@SpringBootApplication在org.springframework.boot.autoconfigure.SpringBootApplication中,Spring Boot的自动装配也都是在org.springframework.boot.autoconfigure项目里实现的
而我们经常看到spring-boot-starter-xxx这种里面主要是定义了依赖包装成一个个启动器,实际实现还是在spring-boot-autoconfigure中,这些都是Spring Boot官方帮我们整合实现并提供开箱即可工具,此外还有一些第三方整合提供以xxx开头的xxx-spring-boot-starter比如阿里巴巴的druid-spring-boot-starter和苞米豆mybatis-plus-boot-starter等
在@SpringBootApplication注解里主要有下面这三个注解
- @SpringBootConfiguration(继承了Configuration,表示当前是注解类)
- @ComponentScan (包含扫描和排除扫描组件配置)
- @EnableAutoConfiguration (在这里开启Spring Boot的自动配置注解功能)@AutoConfigurationPackage**@Import(AutoConfigurationImportSelector.class) **
核心之核心的地方就是借助@import导入AutoConfigurationImportSelector,这个是Spring中ImportSelector接口的实现类,ImportSelect接口是org.springframework.context里的内容,在Spring Framework 3.1版本之后就有,后续我们有时间讨论Spring Framework 的时候再来详说
重要的方法也即是这个getCandidateConfigurations,调用loadFactoryNames,而loadFactoryNames调用loadSpringFactories方法,classLoader.getResources这里就是谜底揭开的时候,通过JDK classLoader加载FACTORIES_RESOURCE_LOCATION(META-INF/spring.factories)文件内容
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
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;
}
?
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}
?
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Map<String, List<String>> result = cache.get(classLoader);
if (result != null) {
return result;
}
?
result = new HashMap<>();
try {
Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
String[] factoryImplementationNames =
StringUtils.commaDelimitedListToStringArray((String) entry.getValue());
for (String factoryImplementationName : factoryImplementationNames) {
result.computeIfAbsent(factoryTypeName, key -> new ArrayList<>())
.add(factoryImplementationName.trim());
}
}
}
?
// Replace all lists with unmodifiable lists containing unique elements
result.replaceAll((factoryType, implementations) -> implementations.stream().distinct()
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)));
cache.put(classLoader, result);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
return result;
}
通过spring-boot-autoconfigure的resource目录下META-INF目录找到spring.factories文件后我们可以看到这里面就是Spring SPI机制实现,在此定义一个规范的路径和文件名,文件内容放置了一个个Spring Boot提供自动装配的组件,而后面我们可想而知Spring Boot底层肯定还是利用反射机制将这些类放到Spring容器中管理,我们就可以通过Spring Boot通用三板斧使用步骤,第一步加坐标依赖starter,第二步启动类中开启使用注解,第三步配置配置文件参数后轻松使用工具类的功能
Starter开发简易剖析
步骤
- 建立autoconfigure工程开发自动配置的实现类xxxProperties.class 提供参数配置实现类,比如redis的host、url等,我们也可以从这里找到所有配置参数信息xxxConnectionConfiguration.class,由@Import注解导入依赖类xxxAutoConfiguration实现类,然后通过Java Config和@Bean注解方式将Java Bean注册到Spring容器里,后续使用则直接从Spring容器中拿即可项目根目录resource建立META-INF文件夹,下面建立spring.factories文件,将自动配置类的全类名方放在org.springframework.boot.autoconfigure.EnableAutoConfiguration里
- 建立spring-boot-starter-xxx工程,管理依赖,如下Redis Starter gradle配置
RedisAutoConfiguration分析
RedisAutoConfiguration实现
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
?
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
?
@Bean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
?
}
Redis Starter依赖
plugins {
id "org.springframework.boot.starter"
}
?
description = "Starter for using Redis key-value data store with Spring Data Redis and the Lettuce client"
?
dependencies {
api(project(":spring-boot-project:spring-boot-starters:spring-boot-starter"))
api("org.springframework.data:spring-data-redis")
api("io.lettuce:lettuce-core")
}
相关推荐
- ETCD 故障恢复(etc常见故障)
-
概述Kubernetes集群外部ETCD节点故障,导致kube-apiserver无法启动。...
- 在Ubuntu 16.04 LTS服务器上安装FreeRADIUS和Daloradius的方法
-
FreeRADIUS为AAARadiusLinux下开源解决方案,DaloRadius为图形化web管理工具。...
- 如何排查服务器被黑客入侵的迹象(黑客 抓取服务器数据)
-
---排查服务器是否被黑客入侵需要系统性地检查多个关键点,以下是一份详细的排查指南,包含具体命令、工具和应对策略:---###**一、快速初步检查**####1.**检查异常登录记录**...
- 使用 Fail Ban 日志分析 SSH 攻击行为
-
通过分析`fail2ban`日志可以识别和应对SSH暴力破解等攻击行为。以下是详细的操作流程和关键分析方法:---###**一、Fail2ban日志位置**Fail2ban的日志路径因系统配置...
- 《5 个实用技巧,提升你的服务器安全性,避免被黑客盯上!》
-
服务器的安全性至关重要,特别是在如今网络攻击频繁的情况下。如果你的服务器存在漏洞,黑客可能会利用这些漏洞进行攻击,甚至窃取数据。今天我们就来聊聊5个实用技巧,帮助你提升服务器的安全性,让你的系统更...
- 聊聊Spring AI Alibaba的YuQueDocumentReader
-
序本文主要研究一下SpringAIAlibaba的YuQueDocumentReaderYuQueDocumentReader...
- Mac Docker环境,利用Canal实现MySQL同步ES
-
Canal的使用使用docker环境安装mysql、canal、elasticsearch,基于binlog利用canal实现mysql的数据同步到elasticsearch中,并在springboo...
- RustDesk:开源远程控制工具的技术架构与全场景部署实战
-
一、开源远程控制领域的革新者1.1行业痛点与解决方案...
- 长安汽车一代CS75Plus2020款安装高德地图7.5
-
不用破解原车机,一代CS75Plus2020款,安装车机版高德地图7.5,有红绿灯读秒!废话不多讲,安装步骤如下:一、在拨号状态输入:在电话拨号界面,输入:*#518200#*(进入安卓设置界面,...
- Zookeeper使用详解之常见操作篇(zookeeper ui)
-
一、Zookeeper的数据结构对于ZooKeeper而言,其存储结构类似于文件系统,也是一个树形目录服务,并通过Key-Value键值对的形式进行数据存储。其中,Key由斜线间隔的路径元素构成。对...
- zk源码—4.会话的实现原理一(会话层的基本功能是什么)
-
大纲1.创建会话...
- Zookeeper 可观测性最佳实践(zookeeper能够确保)
-
Zookeeper介绍ZooKeeper是一个开源的分布式协调服务,用于管理和协调分布式系统中的节点。它提供了一种高效、可靠的方式来解决分布式系统中的常见问题,如数据同步、配置管理、命名服务和集群...
- 服务器密码错误被锁定怎么解决(服务器密码错几次锁)
-
#服务器密码错误被锁定解决方案当服务器因多次密码错误导致账户被锁定时,可以按照以下步骤进行排查和解决:##一、确认锁定状态###1.检查账户锁定状态(Linux)```bash#查看账户锁定...
- zk基础—4.zk实现分布式功能(分布式zk的使用)
-
大纲1.zk实现数据发布订阅...
- 《死神魂魄觉醒》卡死问题终极解决方案:从原理到实战的深度解析
-
在《死神魂魄觉醒》的斩魄刀交锋中,游戏卡死犹如突现的虚圈屏障,阻断玩家与尸魂界的连接。本文将从技术架构、解决方案、预防策略三个维度,深度剖析卡死问题的成因与应对之策,助力玩家突破次元壁障,畅享灵魂共鸣...
你 发表评论:
欢迎- 一周热门
-
-
前端面试:iframe 的优缺点? iframe有那些缺点
-
带斜线的表头制作好了,如何填充内容?这几种方法你更喜欢哪个?
-
漫学笔记之PHP.ini常用的配置信息
-
推荐7个模板代码和其他游戏源码下载的网址
-
其实模版网站在开发工作中很重要,推荐几个参考站给大家
-
[干货] JAVA - JVM - 2 内存两分 [干货]+java+-+jvm+-+2+内存两分吗
-
正在学习使用python搭建自动化测试框架?这个系统包你可能会用到
-
织梦(Dedecms)建站教程 织梦建站详细步骤
-
【开源分享】2024PHP在线客服系统源码(搭建教程+终身使用)
-
2024PHP在线客服系统源码+完全开源 带详细搭建教程
-
- 最近发表
-
- ETCD 故障恢复(etc常见故障)
- 在Ubuntu 16.04 LTS服务器上安装FreeRADIUS和Daloradius的方法
- 如何排查服务器被黑客入侵的迹象(黑客 抓取服务器数据)
- 使用 Fail Ban 日志分析 SSH 攻击行为
- 《5 个实用技巧,提升你的服务器安全性,避免被黑客盯上!》
- 聊聊Spring AI Alibaba的YuQueDocumentReader
- Mac Docker环境,利用Canal实现MySQL同步ES
- RustDesk:开源远程控制工具的技术架构与全场景部署实战
- 长安汽车一代CS75Plus2020款安装高德地图7.5
- Zookeeper使用详解之常见操作篇(zookeeper ui)
- 标签列表
-
- mybatis plus (70)
- scheduledtask (71)
- css滚动条 (60)
- java学生成绩管理系统 (59)
- 结构体数组 (69)
- databasemetadata (64)
- javastatic (68)
- jsp实用教程 (53)
- fontawesome (57)
- widget开发 (57)
- vb net教程 (62)
- hibernate 教程 (63)
- case语句 (57)
- svn连接 (74)
- directoryindex (69)
- session timeout (58)
- textbox换行 (67)
- extension_dir (64)
- linearlayout (58)
- vba高级教程 (75)
- iframe用法 (58)
- sqlparameter (59)
- trim函数 (59)
- flex布局 (63)
- contextloaderlistener (56)