官方文档:https://spring.io/projects/spring-boot#learn
其他笔记:
主要参考: Spring Boot 2 学习笔记(1 / 2)_KISS-CSDN博客
SpringBootWeb模块的默认规则研究_大恐龙的小弟的博客-CSDN博客
01、基础入门-Spring生态圈
Spring能做什么
Spring的生态
覆盖了:
- web开发
- 数据访问
- 安全控制
- 分布式
- 消息服务
- 移动开发
- 批处理
- …
Spring5重大升级
- 响应式编程
- 内部源码设计
基于Java8的一些新特性,如:接口默认实现。重新设计源码架构。
接口的默认实现:即适配器模式(adapter)
- 由于接口的抽象方法太多,而一般情况下我们只需要使用接口的某几个方法,此时继承了接口必须实现所有方法,即便不用,也要加上空方法。
- 此时我们使用适配器实现接口的所有方法,通过继承适配器来重新部分方法即可,避免大量无用的方法实现
为什么用SpringBoot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.link
SpringBoot优点
-
Create stand-alone Spring applications
- 创建独立Spring应用
-
Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
- 内嵌web服务器
-
Provide opinionated ‘starter’ dependencies to simplify your build configuration
- 自动starter依赖,简化构建配置
-
Automatically configure Spring and 3rd party libraries whenever possible
- 自动配置Spring以及第三方功能
-
Provide production-ready features such as metrics, health checks, and externalized configuration
-
提供生产级别的监控、健康检查及外部化配置
-
Absolutely no code generation and no requirement for XML configuration
- 无代码生成、无需编写XML
SpringBoot是整合Spring技术栈的一站式框架
SpringBoot是简化Spring技术栈的快速开发脚手架
SpringBoot缺点
- 人称版本帝,迭代快,需要时刻关注变化
- 封装太深,内部原理复杂,不容易精通
02、基础入门-SpringBoot的大时代背景
微服务
James Lewis and Martin Fowler (2014) 提升微服务完整概念:https://martinfowler.com/microservices/
In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.——James Lewis and Martin Fowler (2014)
- 微服务是一种架构风格
- 一个应用拆分为一组小型服务
- 每个服务运行在自己的进程内,也就是可独立部署和升级
- 服务之间使用轻量级HTTP交互
- 服务围绕业务功能拆分
- 可以由全自动部署机制独立部署
- 去中心化,服务自治。服务可以使用不同的语言、不同的存储技术
分布式
分布式的困难
- 远程调用
- 服务发现
- 负载均衡
- 服务容错
- 配置管理
- 服务监控
- 链路追踪
- 日志管理
- 任务调度
- …
分布式的解决
- SpringBoot + SpringCloud
云原生
原生应用如何上云。 Cloud Native
上云的困难
- 服务自愈:出问题自动复制另一台服务自愈
- 弹性伸缩:自动扩展下线服务
- 服务隔离:一台出问题,不影响其他
- 自动化部署:自动化部署
- 灰度发布:新老版本共存并逐步取代所有老版
- 流量治理:负载均衡
- …
03、基础入门-SpringBoot官方文档架构
- Spring Boot官网
- Spring Boot官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/
- 官方PDF:https://docs.spring.io/spring-boot/docs/2.5.1/reference/pdf/spring-boot-reference.pdf
官网文档架构
权限信息
概览:可以点进去下载pdf
入门
入门进阶
高级特性
监控
部署
命令行应用
插件
小技巧
资源信息:
所有可以配置的属性
配置源信息
自动配置
04、基础入门-SpringBoot-HelloWorld
系统要求
- Java 8
- Maven 3.3+
- IntelliJ IDEA 2019.1.2
Maven配置文件
Maven安装目录下conf/settings.xml新添内容:
1 | <!--设置仓库源--> |
创建maven工程
创建pom.xml文件,引入父项目
1 |
|
添加依赖
1 | <dependencies> |
创建主程序
Maven默认编译src/main/java路径下的资源
创建src/main/java/com/example/MyApplication.java,写入以下代码
1 | import org.springframework.boot.SpringApplication; |
一般写法是只声明主类,不在主类中进行业务处理:
1 | import org.springframework.boot.SpringApplication; |
编写Controller
1 | package com.example.controller; |
SpringBoot配置
在maven工程的resource文件夹中创建application.properties文件。
springboot 所有配置均有默认值,不配置可直接启动
1 | # 设置端口号 |
打包部署
在pom.xml添加部署插件
1 | <build> |
-
mvn clean:清空目录
-
mvn package:打包程序
-
运行:java -jar boot-01-helloworld-1.0-SNAPSHOT.jar
取消cmd的快速编辑模式,否则命令行方式启动SpringBoot时如果点击命令行,可能终止启动
05、基础入门-SpringBoot-依赖管理特性
- 父项目:做依赖管理
1 | <!--依赖管理--> |
starter的含义及支持的所有场景:https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.build-systems.starters
Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the
spring-boot-starter-data-jpa
dependency in your project.
-
开发导入starter场景启动器 1、见到很多 spring-boot-starter-* : *就某种场景 2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入 3、更多SpringBoot所有支持的场景 4、见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
5、所有场景的启动器最底层的依赖
1 | <!--所有场景启动器最底层的依赖--> |
-
无需关注版本号,自动版本仲裁
- 引入依赖默认都可以不写版本
- 引入非版本仲裁的jar,要写版本号。
-
可以修改默认版本号
- 查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
- 在当前项目的pom.xml配置文件,添加如下面的代码。
1 | <properties> |
IDEA快捷键:
ctrl + shift + alt + U
:以图的方式显示项目中依赖之间的关系。alt + ins
:相当于Eclipse的 Ctrl + N,创建新类,新包等。
06、基础入门-SpringBoot-自动配置特性
- 自动配好Tomcat
- 引入Tomcat依赖。
- 配置Tomcat
1 | <dependency> |
- 自动配好SpringMVC
- 引入SpringMVC全套组件
- 自动配好SpringMVC常用组件(功能)
- 自动配好Web常见功能,如:字符编码问题
- SpringBoot帮我们配置好了所有web开发的常见场景
1 | public static void main(String[] args) { |
- 默认的包结构
- 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
- 无需以前的包扫描配置
- 想要改变扫描路径
- @SpringBootApplication(scanBasePackages=“com.lun”)
- @ComponentScan 指定扫描路径
1 |
|
-
SpringBoot各种配置拥有默认值
- 默认配置最终都是映射到某个类上,如:
MultipartProperties
- 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
- 默认配置最终都是映射到某个类上,如:
-
所有自动配置项是按需加载
- 非常多的starter,引入了哪些场景这个场景的自动配置才会开启
- SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面
07、底层注解-@Configuration配置类注解
- 实验环境
基本的bean
- User
1 | package com.example.helloworld.bean; |
- Pet
1 | package com.example.helloworld.bean; |
- 基本使用
- Full模式与Lite模式
- 示例
1 | package com.example.helloworld.config; |
@Configuration测试代码如下:
1 |
|
- 最佳实战
- 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置 类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式(默认)
lite 英 [laɪt] 美 [laɪt] adj. 低热量的,清淡的(light的一种拼写方法);类似…的劣质品
IDEA快捷键:
Alt + Ins
:生成getter,setter、构造器等代码。Ctrl + Alt + B
:查看类的具体实现代码。
08、底层注解-@Import导入组件
- 使用@import导入类,自动调用类的无参构造创建组件,可以放在任何被Springboot管理的组件中,不一定放入config配置类上
@Bean、@Component、@Controller、@Service、@Repository,它们是Spring的基本注解,在Spring Boot中也可以导入容器。
@ComponentScan 在06、基础入门-SpringBoot-自动配置特性有用例。
@Import({User.class, DBHelper.class})给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
1 | //使用无参构造创建两个组件, 默认组件id为全类名 |
测试类:
1 |
|
9、底层注解-@Conditional条件装配
条件装配:满足Conditional指定的条件,则进行组件注入 有很多派生注解
ctrl+h:打开继承树
用@ConditionalOnMissingBean举例说明
- 配置类
1 | /** |
- 主程序类
1 | public static void main(String[] args) { |
10、底层注解-@ImportResource 导入Spring配置文件
比如,公司使用bean.xml文件生成配置bean,然而你为了省事,想继续复用bean.xml,可以使用@ImportResource注解。
bean.xml:
1 |
|
使用方法:
1 |
|
测试类:
1 | public static void main(String[] args) { |
11、底层注解-@ConfigurationProperties配置绑定
如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用
传统方法,十分复杂:
1 | public class getProperties { |
Spring Boot一种配置配置绑定:
@ConfigurationProperties + @Component
- 基本的bean, Car
1 | package com.example.helloworld.bean; |
- 配置文件application.properties
1 | mycar.brand=BYD |
- Controller
1 | package com.example.helloworld.controller; |
Spring Boot另一种配置配置绑定:
@EnableConfigurationProperties + @ConfigurationProperties
@EnableConfigurationProperties(Car.class)的作用
- 开启Car配置绑定功能
- 把Car这个组件自动注册到容器中
1 |
|
1 |
|
12、自动配置-自动包规则原理
Spring Boot应用的启动类:
1 | /** |
分析下@SpringBootApplication
1 |
|
重点分析@SpringBootConfiguration
,@EnableAutoConfiguration
,@ComponentScan
@SpringBootConfiguration
1 |
|
除了元注解之外,就是一个@Configuration
,表示主启动类也是一个配置类。
@ComponentScan
指定扫描哪些路径,Spring注解。
@ComponentScan 在 07、基础入门-SpringBoot-自动配置特性 有用例。
@EnableAutoConfiguration
最重要的注解就是 @EnableAutoConfiguration
1 |
|
重点包含两个注解@AutoConfigurationPackage
,@Import(AutoConfigurationImportSelector.class)
。
@AutoConfigurationPackage
标签名直译为:自动配置包,指定了默认的包规则。
1 |
|
- @Import给容器中导入一个组件Registrar,利用Registrar给容器批量导入一系列组件
- 将指定注解标注的包下的所有组件导入spring IOC容器中。
@Import(AutoConfigurationImportSelector.class) 初始加载自动配置类
- 利用
getAutoConfigurationEntry(annotationMetadata);
给容器中批量导入一些组件 - 调用
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)
获取到所有需要导入到容器中的配置类 - 利用工厂加载
Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);
得到所有的组件 - 从
META-INF/spring.factories
位置来加载一个文件。- 默认扫描我们当前引入的所有包中的
META-INF/spring.factories
路径的文件 spring-boot-autoconfigure-2.3.4.RELEASE.jar
包里面也有META-INF/spring.factories
- 默认扫描我们当前引入的所有包中的
1 | # 文件里面写死了spring-boot一启动就要给容器中加载的所有配置类 共127个 |
127个默认组件
虽然127个场景的所有自动配置启动的时候默认全部加载,但是xxxxAutoConfiguration
按照条件装配规则(@Conditional
),最终会按需配置。
如AopAutoConfiguration
类:
1 |
|
13、自动配置-自动配置流程
SpringBoot自动配置相关,在 spring-boot-autoconfigure-xxx.jar 中
以DispatcherServletAutoConfiguration
的内部类DispatcherServletConfiguration
为例子:
- 整段代码相当于alis,如果MultipartResolver.class类型的组件id不是标准名称multipartResolver,则设置别名为multipartResolver
- 放在用户设置的下载解析器名称不规范
1 |
|
SpringBoot默认会在底层配好所有的组件,但是如果用户自己配置了以用户的优先。
总结:
- SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
- 每个自动配置类按照条件生效,一旦生效默认都会绑定配置文件指定的值。(xxxxProperties类中读取,xxxProperties类和配置文件进行了绑定)
- 生效的配置类就会给容器中装配很多组件
- 只要容器中有这些组件,相当于这些功能就有了
- 定制化配置
- 用户直接自己@Bean替换底层的组件
- 用户去看这个组件是获取的配置文件什么值就去修改
xxxxxAutoConfiguration —> 组件 —> xxxxProperties类中拿值 ----> application.properties
14、最佳实践-SpringBoot应用如何编写
- 引入场景依赖
- 查看自动配置了哪些(选做)
- 自己分析,引入场景对应的自动配置一般都生效了
- 配置文件中 debug=true 开启自动配置报告。
- Negative(不生效)
- Positive(生效)
- 是否需要修改
- 参照文档修改配置项
- 官方文档
- 自己分析。xxxxProperties绑定了配置文件的哪些。
- 自定义加入或者替换组件
- @Bean、@Component…
- 自定义器 XXXXXCustomizer;
- …
- 参照文档修改配置项
15、最佳实践-Lombok简化开发
Lombok用标签方式代替构造器、getter/setter、toString()等鸡肋代码。
spring boot已经管理Lombok。引入依赖:
1 | <dependency> |
IDEA中File->Settings->Plugins,搜索安装Lombok插件。
1 |
|
简化日志开发
1 |
|
17、配置文件-yaml的用法
同以前的properties用法
YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。
非常适合用来做以数据为中心的配置文件。
基本语法
- key: value;kv之间的冒号后有空格
- 大小写敏感
- 使用空格缩进表示层级关系(同一层级左对齐即可)
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果要加单引号’’表示插入转义符、双引号""表示字符串原样输出不转义
数据类型
- 字面量:单个的、不可再分的值。date、boolean、string、number、null
1 | k: v |
- 对象:键值对的集合。map、hash、set、object
1 | #行内写法: |
- 数组:一组按次序排列的值。array、list、queue
1 | #行内写法: |
示例
1 | //绑定配置文件前缀 |
用yaml表示以上对象
写在 application.yml
中,优先级是application.properties
优先
1 | person: |
18、配置文件-自定义类绑定的配置提示
You can easily generate your own configuration metadata file from items annotated with @ConfigurationProperties by using the spring-boot-configuration-processor jar. The jar includes a Java annotation processor which is invoked as your project is compiled.——link
需要在pom.xml中添加依赖
1 | <dependency> |
19、web场景-web开发简介
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)
The auto-configuration adds the following features on top of Spring’s defaults:
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 内容协商视图解析器和BeanName视图解析器
-
Support for serving static resources, including support for WebJars (covered later in this document)).
- 静态资源(包括webjars)
-
Automatic registration of
Converter
,GenericConverter
, andFormatter
beans.- 自动注册
Converter,GenericConverter,Formatter
- 自动注册
-
Support for
HttpMessageConverters
(covered later in this document).- 支持
HttpMessageConverters
(后来我们配合内容协商理解原理)
- 支持
-
Automatic registration of
MessageCodesResolver
(covered later in this document).- 自动注册
MessageCodesResolver
(国际化用)
- 自动注册
-
Static
index.html
support.- 静态index.html 页支持
-
Custom
Favicon
support (covered later in this document).- 自定义
Favicon
- 自定义
-
Automatic use of a
ConfigurableWebBindingInitializer
bean (covered later in this document).- 自动使用
ConfigurableWebBindingInitializer
,(DataBinder负责将请求数据绑定到JavaBean上)
- 自动使用
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. 不用@EnableWebMvc注解。使用 @Configuration + WebMvcConfigurer 自定义规则
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
声明 WebMvcRegistrations 改变默认底层组件
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
使用 @EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC
20、web场景-静态资源规则与定制化
静态资源目录
只要静态资源放在类路径下: called /static
(or /public
or /resources
or /META-INF/resources
访问 : 当前项目根路径/ + 静态资源名
原理: 静态映射/**。
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面。
也可以改变默认的静态资源路径,/static
,/public
,/resources
, /META-INF/resources
失效
1 | resources: |
静态资源访问前缀
1 | spring: |
当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
webjar
可用jar方式添加css,js等资源文件,
例如,添加jquery
1 | <dependency> |
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径。
21、web场景-welcome与favicon功能
欢迎页支持
- 静态资源路径下 index.html
- 可以配置静态资源路径
- 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
1 | spring: |
- controller能处理/index
自定义Favicon
指网页标签上的小图标。
favicon.ico 放在静态资源目录下即可。
1 | spring: |
22、web场景-【源码分析】-静态资源原理
- SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
- SpringMVC功能的自动配置类
WebMvcAutoConfiguration
,生效
1 |
|
给容器中配置的内容:
- 配置文件的相关属性的绑定:WebMvcProperties==spring.mvc、ResourceProperties==spring.resources
1 |
|
WEB场景需要主要分析的包
-
org.sspringframework.boot.autoconfigure: 路径org.springframework.boot:spring-boot-autoconfigure
自动配置原理
-
org.springframework.web.servlet: 路径org.springframework:spring-webmvc
web应用原理
配置类只有一个有参构造器
1 | 有参构造器所有参数的值都会从容器中确定 |
- ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
- WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
- ListableBeanFactory beanFactory Spring的beanFactory
- HttpMessageConverters 找到所有的HttpMessageConverters
- ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。
- DispatcherServletPath
- ServletRegistrationBean 给应用注册Servlet、Filter…
资源处理的默认规则
1 | ... |
根据上述代码,我们可以同过配置禁止所有静态资源规则。
1 | spring: |
静态资源规则:
1 | @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) |
欢迎页的处理规则
1 | ... |
WelcomePageHandlerMapping
的构造方法如下:
1 | WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, |
这构造方法内的代码也解释了web场景-welcome与favicon功能中配置static-path-pattern
了,welcome页面和小图标失效的问题。
参数映射
- @PathVariable("路径变量")
- @RequestHeader("请求头参数")
- @RequestParam("?请求参数")
- @CookieValue("cookie值")
- @RequestBody("请求体,post请求中的表单")
- @RequestAttribute("获取request域属性")
- 即获取前一个请求request.setAttribute("", "")放入的参数
- @MatrixVariable(value = "矩阵变量", pathVar = "path")
- 需要和路径变量合用
- /users/{tom;age=34;name=byd}
- 分号前是访问路径,分号后是矩阵变量,即controller中只需要GetMapping("/users/{path}")
- 路径重写,解决cookie被禁用的问题
- SpringBoot默认关闭矩阵变量
定制SpringMVC
在config类中添加一个 WebMvcConfigurer bean
1 |
|
23、模板引擎
springboot默认打jar包,是一种压缩格式,而jsp不支持在jar包中编译,因此springboot默认不支持jsp,引入了第三方模板引擎
Thymeleaf:简单,自然语言的模板,但不高效。
24、数据库
查看版本:
1 | 父项目spring boot |
1 | spring: |
25、整合第三方技术到spring boot 中
第三方是否提供starter,提供可以直接使用,不提供则需要手动导入自定义使用
导入依赖
1 | <dependency> |
配置文件
1 | <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> |