springboot3-核心特性
第一章、springboot3-快速入门
1.简介
1.前置知识
- java17
- spring、springmvc、mybatis
- Maven、IDEA
2.环境要求
环境&工具 | 版本 |
---|---|
springboot | 3.0.5+ |
IDEA | 2021.2.1+ |
java | 17+ |
Maven | 3.5+ |
tomcat | 10.0+ |
servlet | 5.0+ |
GraaIVM Community | 22.3+ |
Native Build Tools | 0.9.19+ |
3.springboot是什么
springboot帮我们简单、快速地创建一个独立的、生产级别的spring应用(springboot的底层是spring)
大多数springboot应用只需要编写少量配置即可快速整合spring平台以及第三方技术
特性:
-
快速创建独立spring应用
- SSM:导包、写配置、启动运行
-
直接嵌入Tomcat、Jetty or Undertow(无需部署war包)【Servlet容器】
- linux 、java、tomcat、mysql:war放到tomcat的webapps下
- jar:java环境;java - jar
-
重点:提供可选的starter,简化应用整合
-
- 场景启动器(starter):web、json、邮件、oss(对象存储)、异步、定时任务、缓存…
- 导包一堆,控制好版本。
- 为每一种场景准备了一个依赖; web-starter。mybatis-starter
- 场景启动器(starter):web、json、邮件、oss(对象存储)、异步、定时任务、缓存…
-
**重点:**按需自动配置 Spring 以及 第三方库
-
-
如果这些场景我要使用(生效)。这个场景的所有配置都会自动配置好。
-
约定大于配置:每个场景都有很多默认配置。
-
自定义:配置文件中修改几项就可以
-
- 提供生产级特性:如 监控指标、健康检查、外部化配置等
-
-
-
- 监控指标、健康检查(k8s)、外部化配置
-
无代码生成、无xml
总结:简化开发,简化配置,简化整合,简化部署,简化监控,简化运维。
-
2.快速体验
场景:浏览器发送/hello请求,返回"Hello springboot3"
1.开发流程
1.创建项目
maven项目
<!-- 所有springboot项目都必须继承自 spring-boot-starter-parent -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
</parent>
2.导入场景
<dependencies>
<!-- web开发的场景启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3.主程序
@SpringBootApplication //这是一个SpringBoot应用
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class,args);
}
}
4.业务
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "Hello,Spring Boot 3!";
}
}
5.测试
默认启动访问:localhost:8080
6.打包
<!-- SpringBoot应用打包插件-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
mvn clean package
把项目打成可执行的jar包
java -jar demo.jar
启动项目
2.特性小结
1.简化整合
导入相关的场景,拥有相关的功能。场景启动器
默认支持的所有场景:https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.build-systems.starters
- 官方提供的场景:命名为:
spring-boot-starter-*
- 第三方提供场景:命名为:
*-spring-boot-starter
场景一导入,万物皆就绪
2.简化开发
无需编写任何配置,直接开发业务
3.简化配置
application.properties
:
- 集中式管理配置。只需要修改这个文件就行 。
- 配置基本都有默认值
- 能写的所有配置都在: https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties
4.简化部署
打包可执行的jar包
linux服务器上有java环境
5.简化运维
修改配置(外部放一个application.properties文件)、监控、健康检查
3.spring initializr创建向导
一键创建好整个项目结构
3.应用分析
1.依赖管理机制
思考:
1、为什么导入starter-web
所有相关依赖都导入进来?
- 开发什么场景,导入什么场景启动器。
- maven依赖传递原则。A-B-C: A就拥有B和C
- 导入 场景启动器。 场景启动器 自动把这个场景的所有核心依赖全部导入进来
2、为什么版本号都不用写?
- 每个boot项目都有一个父项目
spring-boot-starter-parent
- parent的父项目是
spring-boot-dependencies
- 父项目 版本仲裁中心,把所有常见的jar的依赖版本都声明好了。
- 比如:
mysql-connector-j
3、自定义版本号
-
利用maven的就近原则
-
- 直接在当前项目
properties
标签中声明父项目用的版本属性的key- 直接在导入依赖的时候声明版本
- 直接在当前项目
4、第三方的jar包
-
boot父项目没有管理的需要自行声明好
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.16</version> </dependency>
2.自动配置机制
1.初步理解
-
自动配置的tomcat、springmvc等
-
导入场景,容器中就会自动装配好这个场景的核心组件
-
以前:DispatcherServlet、ViewResolver、CharacterEncodingFilter…
-
现在:自动配置好的这些组件
-
验证:容器中有了什么组件,就具有什么功能
public static void main(String[] args) { //java10: 局部变量类型的自动推断 var ioc = SpringApplication.run(MainApplication.class, args); //1、获取容器中所有组件的名字 String[] names = ioc.getBeanDefinitionNames(); //2、挨个遍历: // dispatcherServlet、beanNameViewResolver、characterEncodingFilter、multipartResolver // SpringBoot把以前配置的核心组件现在都给我们自动配置好了。 for (String name : names) { System.out.println(name); } }
-
-
默认的包扫描规则
@SpringBootApplication
标注的类即是主程序类- SpringBoot只会扫描主程序所在的包及其下面的子包,自动进行ComponentScan功能
- 自定义扫描路径
@SpringBootApplication(scanBasePackeges = "com.xuan")
@ComponentScan("com.xuan")
直接指定扫描的路径
-
配置默认值
- 配置文件的所有配置项是和某个类的对象值进行一一绑定
- 绑定了配置文件中每一项值的类:属性类
- 比如
ServerProperties
绑定了所有tomcat服务器有关的配置MultipartProperties
绑定了所有文件上传相关的配置- …参照官方文档:或者参照绑定的属性类
-
按需加载自动配置
- 导入场景
spring-boot-starter-web
- 场景启动器除了会导入相关功能依赖,导入一个
spring-boot-starter
,是所有starter
的starter
,基础核心starter spring-boot-starter
导入了一个包spring-boot-autoconfigure
。包里都是各种场景的AutoConfiguration
自动配置类- 虽然全场景的自动配置都在
spring-boot-autoconfigure
这个 包,但是不是全部开启的- 导入哪个场景就开启哪个自动配置
- 导入场景
总结:导入场景启动器、触发spring-boot-autoconfigure
这个包的自动配置生效,容器中就会具有相关场景的功能
2.完整流程
思考:
- Springboot怎么实现导一个starter,写一些简单配置,应用就能跑起来,我们无需关心整合
- 为什么tomcat的端口号可以配置在application.properties中,并且tomcat能启动成功
- 导入场景后哪些自动配置能生效
自动动配置流程细节梳理
-
导入
starter-web
:导入了web开发场景- 1、场景启动器导入了相关场景的所有依赖:
starter-json
、starter-tomcat
、springmvc
- 2、每个场景启动器都引入了一个
spring-boot-starter
,核心场景启动器。 - 3、核心场景启动器引入了
spring-boot-autoconfigure
包。 - 4、
spring-boot-autoconfigure
里面囊括了所有场景的所有配置。 - 5、只要这个包下的所有类都能生效,那么相当于SpringBoot官方写好的整合功能就生效了。
- 6、SpringBoot默认却扫描不到
spring-boot-autoconfigure
下写好的所有配置类。(这些配置类给我们做了整合操作),默认只扫描主程序所在的包。
2、主程序:
@SpringBootApplication
-
1、
@SpringBootApplication
由三个注解组成@SpringBootConfiguration
、@EnableAutoConfiguratio
、@ComponentScan
-
2、SpringBoot默认只能扫描自己主程序所在的包及其下面的子包,扫描不到
spring-boot-autoconfigure
包中官方写好的配置类- 3、
@EnableAutoConfiguration
:SpringBoot 开启自动配置的核心。
- 3、
-
-
- 是由
@Import(AutoConfigurationImportSelector.class)
提供功能:批量给容器中导入组件。
-
- SpringBoot启动会默认加载 142个配置类。
-
- 这142个配置类来自于
spring-boot-autoconfigure
下META-INF/spring/**org.springframework.boot.autoconfigure.AutoConfiguration**.imports
文件指定的
- 这142个配置类来自于
- 项目启动的时候利用 @Import 批量导入组件机制把
autoconfigure
包下的142xxxxAutoConfiguration
类导入进来(自动配置类) - 虽然导入了
142
个自动配置类
- 是由
-
-
4、按需生效:
-
- 并不是这
142
个自动配置类都能生效- 每一个自动配置类,都有条件注解
@ConditionalOnxxx
,只有条件成立,才能生效
- 每一个自动配置类,都有条件注解
- 并不是这
3、
xxxxAutoConfiguration
自动配置类- 1、给容器中使用@Bean 放一堆组件。
- 2、每个自动配置类都可能有这个注解
@EnableConfigurationProperties(ServerProperties.class)
,用来把配置文件中配的指定前缀的属性值封装到xxxProperties
属性类中 - 3、以Tomcat为例:把服务器的所有配置都是以
server
开头的。配置都封装到了属性类中。 - 4、给容器中放的所有组件的一些核心参数,都来自于
xxxProperties
。xxxProperties
都是和配置文件绑定。 - 只需要改配置文件的值,核心组件的底层参数都能修改
4、写业务,全程无需关心各种整合(底层这些整合写好了,而且也生效了)
核心流程总结:
1、导入
starter
,就会导入autoconfigure
包。2、
autoconfigure
包里面 有一个文件META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
,里面指定的所有启动要加载的自动配置类3、@EnableAutoConfiguration 会自动的把上面文件里面写的所有自动配置类都导入进来。xxxAutoConfiguration 是有条件注解进行按需加载
4、
xxxAutoConfiguration
给容器中导入一堆组件,组件都是从xxxProperties
中提取属性值5、
xxxProperties
又是和配置文件进行了绑定**效果:**导入
starter
、修改配置文件,就能修改底层行为。 - 1、场景启动器导入了相关场景的所有依赖:
3.如何学好Springboot
框架的框架、底层基于Spring。能调账每一个场景的底层行为。100%的项目一定会用到底层自定义
- 理解自动配置原理
- 导入starter—> 生效xxxxAutoConfiguration—>组件—>xxxProperties—>配置文件
- 理解其他框架底层
- 拦截器
- 可以随时定制化任何组件
- 配置文件
- 自定义组件
普通开发:导入starter、Controller、Service、Mapper、偶尔修改配置文件
高级开发:自定义组件、自定义配置、自定义starter
核心:
- 这个场景自动配置导入了哪些组件,我们能不能AutoWired进来使用
- 能不能通过修改配置改变组件的一些默认参数
- 需不需要自己完全定义这个组件
- 场景的定制化
最佳实战:
- 选场景,导入到项目
- 官方:starter
- 第三方:去仓库搜
- 写配置,改配置文件关键项
- 数据库参数(连接地址、账号密码…)
- 分析这个场景给我们导入了哪些能用的组件
- 自动装配这些组件进行后续使用
- 不满意boot提供的自动配好的默认组件
- 定制化
- 改配置
- 自定义组件
- 定制化
整合redis:
- 选场景:
spring-boot-starter-data-redis
- 场景AutoConfiguration就是这个场景的自动配置类
- 写配置:
- 分析到这个场景的自动配置类开启了哪些属性绑定关系
@EnableConfigurationProperties(RedisProperties.class)
- 修改redis相关的配置
- 分析组件:
- 分析到RedisAutoConfiguration给容器中放了
StringRedisTemplate
(自己知道) - 给业务代码中自动装配
StringRedisTemplate
进行增删改查操作
- 分析到RedisAutoConfiguration给容器中放了
- 定制化
- 修改配置文件
- 自定义组件,自己给容器中放一个
StringRedisTemplate
4.核心技能
1.常用注解
SpringBoot摒弃XML配置方式,改为全注解驱动
1.组件注册
@Configuration、@SpringBootCOnfiguration
@Bean、@Scope
@Controller、@Service、@Repository、@Component
@Import
@ComponentScan
步骤:
- @Configuration编写一个配置类
- 在配置类中,自定义方法给容器中注册组件,配合@Bean
- 或使用@Import导入第三方的组件
2.条件注解
如果注解指定的条件成立,则触发指定行为
@ConditionalOnXxx
@ConditionalOnClass:如果类路径中存在这个类,则触发指定行为
@ConditionalOnMissingClass:如果类路径中不存在这个类,则触发指定行为
@ConditionalOnBean:如果容器中存在这个Bean(组件),则触发指定行为
@ConditionalOnMissingBean:如果容器中不存在这个Bean(组件),则触发指定行为
场景:
- 如果存在
FastsqlException
这个类,给容器中放一个Cat
组件,名为cat01- 否则,就给容器中放一个
Dog
组件,名为dog01- 如果系统中有
dog01
这个组件,就给容器中放一个user组件,名为zhangsan- 否则,就放一个User,名为lisi
@ConditionalOnBean(value=组件类型,name=组件名字):判断容器中是否有这个类型的组件,并且名字是指定的值
@ConditionalOnRepositoryType (org.springframework.boot.autoconfigure.data)
@ConditionalOnDefaultWebSecurity (org.springframework.boot.autoconfigure.security)
@ConditionalOnSingleCandidate (org.springframework.boot.autoconfigure.condition)
@ConditionalOnWebApplication (org.springframework.boot.autoconfigure.condition)
@ConditionalOnWarDeployment (org.springframework.boot.autoconfigure.condition)
@ConditionalOnJndi (org.springframework.boot.autoconfigure.condition)
@ConditionalOnResource (org.springframework.boot.autoconfigure.condition)
@ConditionalOnExpression (org.springframework.boot.autoconfigure.condition)
@ConditionalOnClass (org.springframework.boot.autoconfigure.condition)
@ConditionalOnEnabledResourceChain (org.springframework.boot.autoconfigure.web)
@ConditionalOnMissingClass (org.springframework.boot.autoconfigure.condition)
@ConditionalOnNotWebApplication (org.springframework.boot.autoconfigure.condition)
@ConditionalOnProperty (org.springframework.boot.autoconfigure.condition)
@ConditionalOnCloudPlatform (org.springframework.boot.autoconfigure.condition)
@ConditionalOnBean (org.springframework.boot.autoconfigure.condition)
@ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition)
@ConditionalOnMissingFilterBean (org.springframework.boot.autoconfigure.web.servlet)
@Profile (org.springframework.context.annotation)
@ConditionalOnInitializedRestarter (org.springframework.boot.devtools.restart)
@ConditionalOnGraphQlSchema (org.springframework.boot.autoconfigure.graphql)
@ConditionalOnJava (org.springframework.boot.autoconfigure.condition)
3.属性绑定
@ConfigurationProperties:声明组件的属性和配置文件哪些前缀开始项进行绑定
@EnableConfiguraionProperties:快速注册注解:
- 场景:SpringBoot默认只扫描自己主程序所在的包。如果导入第三方包,即使组件上标注了 @Component、@ConfigurationProperties 注解,也没用。因为组件都扫描不进来,此时使用这个注解就可以快速进行属性绑定并把组件注册进容器
将容器中任意组件(Bean)的属性值和配置文件的配置项的值进行绑定
- 1、给 容器中注册组件(@Component、@Bean)
- 2、使用@ConfigurationProperties声明组件和配置文件的哪些属性进行绑定
2.YAML配置文件
痛点:SpringBoot集中化配置管理,
application.properties
问题:配置多以后难阅读和修改,层级结构辨识度不高
YAML是"YAML Ain’t a Markup Language"(YAML 不是一种标记语言)。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(是另一种标记语言)。
- 设计目标,就是方便人类读写
- 层次分明,更适合做配置文件
- 使用
.yaml
或.yml
作为文件后缀
1.基本语法
- 大小写敏感
- 使用缩进表示层级关系,k: v,使用空格分割k,v
- 缩进时不允许使用Tab键,只允许使用空格。换行
- 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
- # 表示注释,从这个字符一直到行尾,都会被解析器忽略。
支持的写法:
- 对象:键值对的集合,如:映射(map)/ 哈希(hash) / 字典(dictionary)
- 数组:一组按次序排列的值,如:序列(sequence) / 列表(list)
- 纯量:单个的、不可再分的值,如:字符串、数字、bool、日期
2.实例
@Component
@ConfigurationProperties(prefix = "person") //和配置文件person前缀的所有配置进行绑定
@Data //自动生成JavaBean属性的getter/setter
//@NoArgsConstructor //自动生成无参构造器
//@AllArgsConstructor //自动生成全参构造器
public class Person {
private String name;
private Integer age;
private Date birthDay;
private Boolean like;
private Child child; //嵌套对象
private List<Dog> dogs; //数组(里面是对象)
private Map<String,Cat> cats; //表示Map
}
@Data
public class Dog {
private String name;
private Integer age;
}
@Data
public class Child {
private String name;
private Integer age;
private Date birthDay;
private List<String> text; //数组
}
@Data
public class Cat {
private String name;
private Integer age;
}
properties表示法
person.name=张三
person.age=18
person.birthDay=2010/10/12 12:12:12
person.like=true
person.child.name=李四
person.child.age=12
person.child.birthDay=2018/10/12
person.child.text[0]=abc
person.child.text[1]=def
person.dogs[0].name=小黑
person.dogs[0].age=3
person.dogs[1].name=小白
person.dogs[1].age=2
person.cats.c1.name=小蓝
person.cats.c1.age=3
person.cats.c2.name=小灰
person.cats.c2.age=2
yaml表示法
person:
name: 张三
age: 18
birthDay: 2010/10/10 12:12:12
like: true
child:
name: 李四
age: 20
birthDay: 2018/10/10
text: ["abc","def"]
dogs:
- name: 小黑
age: 3
- name: 小白
age: 2
cats:
c1:
name: 小蓝
age: 3
c2: {name: 小绿,age: 2} #对象也可用{}表示
3.细节
- birthDay推荐写成birth-day
- 文本:
- 单引号不会转义【\n则为普通字符串显示】
- 双引号会转义【\n会显示为换行符】
- 大文本
|
开头,大文本写在下层,保留文本格式,换行符正确显示>
开头,大文本写在下层,折叠换行符
- 多文档合并
- 使用
–--
可以把多个yaml文档合并在一个文档中, 每个文档区依然认为内容独立
- 使用
4.小技巧:使用lombok
3.日志配置
规范:项目开发不要编写
System.out.println()
,应该使用日志记录信息
1.简介
-
Spring使用
commons-logging
作为内部日志,但底层日志实现是开放的。可对接其他日志框架。 -
- spring5及以后
commons-logging
被spring直接自己写了。
- spring5及以后
-
支持
jul
,log4j2
,logback
。SpringBoot 提供了默认的控制台输出配置,也可以配置输出为文件。 -
logback
是默认使用的。 -
虽然日志框架很多,但是我们不用担心,使用 SpringBoot 的默认配置就能工作的很好。
SpringBoot怎么把日志默认配置好的
- 每个
starter
场景,都会导入一个核心场景spring-boot-starter
- 核心场景引入了日志的所用功能
spring-boot-starter-logging
- 默认使用了
logback+slf4j
组合作为默认底层日志 - 日志是系统已启动就要用,
xxxAutoConfiguration
是系统启动好了以后放好的组件,后来用的 - 日志是利用监听器机制配置好的。
ApplicationListener
- 日志所有的配置都可以通过修改配置文件 实现,以
loggin
开始的所有配置
2.日志格式
2023-03-31T13:56:17.511+08:00 INFO 4944 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-03-31T13:56:17.511+08:00 INFO 4944 --- [ main] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.7]
默认输出格式:
- 时间和日期:毫秒级精度
- 日志级别:
ERROR
,WARN
,INFO
,DEBUG
,orTRACE
- 进程ID
---
:消息分隔符- 线程名:使用[]包含
- Logger名:通常是产生日志的类名
- 消息:日志记录的内容
注意:logback没有FATAL
级别,对应的是ERROR
默认值:参照:spring-boot
包additional-spring-configuration-metadata.json
文件
默认输出格式值:%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}
可修改为:'%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} ===> %msg%n'
3.记录日志
Logger logger = LoggerFactory.getLogger(getClass());
或者使用Lombok的@Slf4j注解
4.日志级别
-
由高到低:
ALL,TRACE, DEBUG, INFO, WARN, ERROR,FATAL,OFF
;- 只会打印指定级别及以上的日志
- All:打印所有日志
- TRACE:追踪框架 详细流程日志,一般不使用
- DEBUG:开发 调试细节日志
- INFO:关键、感兴趣信息日志
- WARN:警告但不是错误的信息日志,比如:版本过时
- FATAL:知名错误日志,比如jvm系统崩溃
- OFF:关闭所有日志记录
-
不指定级别的所有类,都使用root指定的级别作为默认级别
-
springboot日志默认级别是info
- 在application.properties/yaml中配置logging.level.**=**指定日志级别
- level可取范围:TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF,定义在LogLevel类中
- root的logger-name叫root,可以配置logging.level.root=warn,代表所有未指定的日志级别都是用root的warn级别
5.日志分组
比较有用的技巧是:
将相关的logger分组在一起,统一配置。SpringBoot 也支持。比如:Tomcat 相关的日志统一设置
logging.group.tomcat=org.apache.catalina,org.apache.coyote,org.apache.tomcat
logging.level.tomcat=trace
springboot预定义两个组
Name | Logger |
---|---|
web | org.springframework.core.codec, org.springframework.http, org.springframework.web, org.springframework.boot.actuate.endpoint.web, org.springframework.boot.web.servlet.ServletContextInitializerBeans |
sql | org.springframework.jdbc.core,org.hibernate.SQl,org.joop.tools.LoggerListener |
6.文件输出
springBoot默认只把日志写在控制台,如果想额外记录到日志,可以在application.properties
中添加``logging.file.nameor
logging.file.path`配置项
logging.file.name | logging.file.path | 示例 | 效果 |
---|---|---|---|
未指定 | 未指定 | 仅控制台输出 | |
指定 | 未指定 | my.log | 写出指定文件。可以加路径 |
未指定 | 指定 | /var /log | 写出指定目录,文件名为spring.log |
指定 | 指定 | 以logging.file.name为准 |
7.文档归档与滚动切割
归档:每天的日志单独存到一个文档中
切割: 每个文件10MB,超过这个大小就切割成另外一个文件存储
- 每天的日志可应该独立分割出来存档。如果使用logback(springboot默认 整合),可以通过application.properties/yaml文件指定日志滚动规则
- 如果是其他日志系统,需要自行配置(添加log4j2.xml或者log4j2-spring.xml)
- 支持的滚动规则如下
配置项 | 描述 |
---|---|
logging.logback.rollingpolicy.file-name-pattern | 日志存档的文件名格式(默认值:${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz) |
logging.logback.rollingpolicy.clean-history-on-start | 应用启动时是否清除以前存档(默认为false) |
logging.logback.rollingpolicy.max-file-size | 存档前,每个日志的最大大小(默认值:10MB) |
logging.logback.rollingpolicy.total-size-cap | 日志删除之前,可以容纳的最大大小(默认值:0B)。设置1GB则磁盘存储超过1GB日志之后就会删除旧的日志文件 |
logging.logback.rollingpolicy.max-history | 日志文件保存的最大天数(默认是为7) |
8.自定义配置
通常我们配置application.properties就够了。当然也可以自定义。比如:
日志系统 | 自定义 |
---|---|
Logback | logback-spring.xml,logback-spring.groovy logback.xml or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK(Java Util Logging) | logging.properties |
如果可能,我们建议您在日志配置中使用-spring变量(例如logback-spring.xml而不是logback.xml)如果您使用标准配置文件,spring无法完全控制日志初始化
最佳实战:自己要写配置,配置文件名加上xxx-spring.xml
9.切换日志组合
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
第二章、springboot3-web开发
spring bootde web开发能力,由springmvc提供
0.WebMvcAutoConfiguration原理
1.生效条件
@AutoConfiguration(
after = {DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class}
)
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@ImportRuntimeHints({WebResourcesRuntimeHints.class})
public class WebMvcAutoConfiguration {
2.效果
- 放了两个filter:
HiddenHttpMethodFilter
;页面表单提交Rest请求(GET、POST、PUT、DELETE)FormContentFilter
:表单内容Filter,GET、POST请求可以携带数据
- 给容器中放了
WebMvcConfigurer
组件;给springmvc添加各种定制功能- 所有的功能最终会和配置文件进行绑定
- WebMvcProperties:
spring.mvc
配置文件 - WebProperties:
spring.web
配置文件
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class) //额外导入了其他配置
@EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware{
}
3.WebMvcConfigurer接口
提供了配置springmvc底层的所有组件入口
4.静态资源规则源码
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
//1、
addResourceHandler(registry, this.mvcProperties.getWebjarsPathPattern(),
"classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
- 规则一:访问:
/webjars/**
路径就去classpath:/METE-INF-resources/webjars/
下找资源- maven导入依赖
- 规则二:访问:
/**
路径就去静态资源默认的四个位置找资源
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
- 规则三:静态资源默认都有缓存规则的设置
- 所有缓存的设置,直接通过配置文件:
spring.web
- cachePeriod:缓存周期;多久不用找服务器要新的。默认为没有,以s为单位
- CacheControl:HTTP缓存控制;https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching
- useLastModified:是否使用最后一次修改。配合HTTP Cache规则
- 所有缓存的设置,直接通过配置文件:
如果浏览器访问了一个静态资源
index.js
,如果服务这个资源没有发生变化,下次访问的时候就可以直接让浏览器用自己缓存的东西,而不用给服务器发送请求registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod())); registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl()); registration.setUseLastModified(this.resourceProperties.getCache().isUseLastModified());
5.EnableWebMvcConfiguration源码
//SpringBoot 给容器中放 WebMvcConfigurationSupport 组件。
//我们如果自己放了 WebMvcConfigurationSupport 组件,Boot的WebMvcAutoConfiguration都会失效。
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(WebProperties.class)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware
{
}
-
HandlerMapping
: 根据请求路径/a
找那个handler能处理请求 -
WelcomePageHandlerMapping
:
-
-
- 访问
/**
路径下的所有请求,都在以前四个静态资源路径下找,欢迎页也一样- 找
index.html
:只要静态资源的位置有一个index.html
页面,项目启动默认访问
- 找
- 访问
-
6.为什么容器中放一个WebMvcConfigurer就能配置底层行为
- WebMvcAutoConfiguration 是一个自动配置类,它里面有一个
EnableWebMvcConfiguration
EnableWebMvcConfiguration
继承与DelegatingWebMvcConfiguration
,这两个都生效DelegatingWebMvcConfiguration
利用 DI 把容器中 所有WebMvcConfigurer
注入进来- 别人调用
DelegatingWebMvcConfiguration
的方法配置底层规则,而它调用所有WebMvcConfigurer
的配置底层方法。
7.WebMvcConfigurationSupport
提供了很多的默认设置
判断系统中是否有相应的类:如果有,就加入相应的HttpMessageConverter
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader);
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
1.web场景
1.自动配置
-
整合web场景
<dependency> <groupId>org.springframework.</groupId> <artifactId>spring-boot-s tarter-web</artifactId> </dependency>
-
引入了autoconfigure功能
-
@EnableAutoConfiguration
注解使用@Import(AutoConfigurationImportSelector.class)
批量导入组件 -
加载
META -INF/spring/org.spring framework.boot.autoconfigure.AutoConfiguration.imports
文件中配置的所有组件 -
所有的自动配置类如下
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration ====以下是响应式web场景和现在的没关系====== org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.ReactiveMultipartAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.WebSessionIdResolverAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration ================以上没关系================= org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
-
绑定了配置文件的一堆配置项
- springmvc的所有配置
spring.mvc
- Web场景的通用配置
spring.web
- 文件上传的配置
spring.servlet.multipart
- 服务器的配置
server
。比如:编码方式
- springmvc的所有配置
2.默认效果
默认配置:
-
包含了
ContentNegotiatingViewResolver
和BeanNameViewResolver
组件,方便视图解析 -
默认的静态资源处理机制:静态资源放在static文件夹下的即可直接访问
-
自动注册了
Converter
,GenericConverter
,Formatter
组件,适配常见的数据类型转换和格式化需求 -
支持
HttpMesageConverters
,可以方便返回json等数据类型 -
注册
MessageCodesResolver
,方便国际化及错误消息处理 -
支持静态
index.html
-
自动使用
ConfigurableWebBindingInitializer
,实现消息处理,数据绑定,类型转换等功能重要:
- 如果想保持boot mvc的默认配置,并且自定义更多的 mvc配置,如:interceptors、formatters,viewcontrollers等。可以使用@Configuration注解添加一个WebMvcConfigurer类型的配置类,并不标注@EnableWebMvc
- 如果想保持boot mvc的默认配置,但要自定义核心组件实例,比如:
RequestMappingHandlerMapping,RequestMappingHandlerAdapter ,或ExceptionHandlerExceptionResolver,给容器中放一个WebMvcRegistrations组件即可 - 如果想全面接管springmvc,@Configuration标注一个配置类,并加上@EnableWebMvc注解,实现WebMvcConfigurer接口
2.静态资源
1.默认规则
1.静态资源映射
静态资源映射规则在 WebMvcAutoConfiguration 中进行了定义:
-
/webjars/** 的所有路径 资源都在 classpath:/META-INF/resources/webjars/
-
/** 的所有路径 资源都在 classpath:/META-INF/resources/、classpath:/resources/、classpath:/static/、classpath:/public/
-
所有静态资源都定义了缓存规则。【浏览器访问过一次,就会缓存一段时间】,但此功能参数无默认值
-
- period: 缓存间隔。 默认 0S;
- cacheControl:缓存控制。 默认无;
- useLastModified:是否使用lastModified头。 默认 false;
2.静态资源缓存
如前面所述
-
所有静态资源都定义了缓存规则。【浏览器访问过一次,就会缓存一段时间】,但此功能参数无默认值
-
- period: 缓存间隔。 默认 0S;
- cacheControl:缓存控制。 默认无;
- useLastModified:是否使用lastModified头。 默认 false;
3.欢迎页
欢迎页规则在 WebMvcAutoConfiguration 中进行了定义:
- 在静态资源目录下找 index.html
- 没有就在 templates下找index模板页
4.Favicon
- 在静态资源目录下找 favicon.ico
5.缓存实验
server.port=9000
#1、spring.web:
# 1.配置国际化的区域信息
# 2.静态资源策略(开启、处理链、缓存)
#开启静态资源映射规则
spring.web.resources.add-mappings=true
#设置缓存
#spring.web.resources.cache.period=3600
##缓存详细合并项控制,覆盖period配置:
## 浏览器第一次请求服务器,服务器告诉浏览器此资源缓存7200秒,7200秒以内的所有此资源访问不用发给服务器请求,7200秒以后发请求给服务器
spring.web.resources.cache.cachecontrol.max-age=7200
#使用资源 last-modified 时间,来对比服务器和浏览器的资源是否相同没有变化。相同返回 304
spring.web.resources.cache.use-last-modified=true
2.自定义静态资源规则
自定i一静态资源路径、自定义缓存规则
1.配置方式
spring.mvc
: 静态资源访问前缀路径
spring.web
:
- 静态资源目录
- 静态资源缓存策略
#1、spring.web:
# 1.配置国际化的区域信息
# 2.静态资源策略(开启、处理链、缓存)
#开启静态资源映射规则
spring.web.resources.add-mappings=true
#设置缓存
spring.web.resources.cache.period=3600
##缓存详细合并项控制,覆盖period配置:
## 浏览器第一次请求服务器,服务器告诉浏览器此资源缓存7200秒,7200秒以内的所有此资源访问不用发给服务器请求,7200秒以后发请求给服务器
spring.web.resources.cache.cachecontrol.max-age=7200
## 共享缓存
spring.web.resources.cache.cachecontrol.cache-public=true
#使用资源 last-modified 时间,来对比服务器和浏览器的资源是否相同没有变化。相同返回 304
spring.web.resources.cache.use-last-modified=true
#自定义静态资源文件夹位置
spring.web.resources.static-locations=classpath:/a/,classpath:/b/,classpath:/static/
#2、 spring.mvc
## 2.1. 自定义webjars路径前缀
spring.mvc.webjars-path-pattern=/wj/**
## 2.2. 静态资源访问路径前缀
spring.mvc.static-path-pattern=/static/**
2.代码方式
- 容器中只要有一个 WebMvcConfigurer 组件。配置的底层行为都会生效
- @EnableWebMvc //禁用boot的默认配置
@Configuration //这是一个配置类
public class MyConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//保留以前规则
//自己写新的规则。
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/a/","classpath:/b/")
.setCacheControl(CacheControl.maxAge(1180, TimeUnit.SECONDS));
}
}
@Configuration //这是一个配置类,给容器中放一个 WebMvcConfigurer 组件,就能自定义底层
public class MyConfig /*implements WebMvcConfigurer*/ {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/a/", "classpath:/b/")
.setCacheControl(CacheControl.maxAge(1180, TimeUnit.SECONDS));
}
};
}
}
3.路径匹配
Spring5.3 之后加入了更多的请求路径匹配的实现策略;
以前只支持 AntPathMatcher 策略, 现在提供了 PathPatternParser 策略。并且可以让我们指定到底使用那种策略。
1.Ant风格路径用法
Ant风格的路径模式语法具有以下规则:
*
:表示任意数量的字符。?
:表示任意一个字符。**
:表示任意数量的目录。{}
:表示一个命名的模式占位符。[]
:表示字符集合,例如[a-z]表示小写字母。
例如:
*.html
匹配任意名称,扩展名为.html的文件。/folder1/*/*.java
匹配在folder1目录下的任意两级目录下的.java文件。/folder2/**/*.jsp
匹配在folder2目录下任意目录深度的.jsp文件。/{type}/{id}.html
匹配任意文件名为{id}.html,在任意命名的{type}目录下的文件。
注意:Ant 风格的路径模式语法中的特殊字符需要转义,如:
- 要匹配文件路径中的星号,则需要转义为\*。
- 要匹配文件路径中的问号,则需要转义为\?。
2.模式切换
AntPathMatcher 与
PathPatternParser
- PathPatternParser 在 jmh 基准测试下,有 6~8 倍吞吐量提升,降低 30%~40%空间分配率
- PathPatternParser 兼容 AntPathMatcher语法,并支持更多类型的路径模式
- PathPatternParser "*" 多段匹配的支持仅允许在模式末尾使用*
@GetMapping("/a*/b?/{p1:[a-f]+}")
public String hello(HttpServletRequest request,
@PathVariable("p1") String path) {
log.info("路径变量p1: {}", path);
//获取请求路径
String uri = request.getRequestURI();
return uri;
}
总结:
- 使用默认的路径匹配规则,是由 PathPatternParser 提供的
- 如果路径中间需要有 **,替换成ant风格路径
# 改变路径匹配策略:
# ant_path_matcher 老版策略;
# path_pattern_parser 新版策略;
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
4.内容协商
一套系统适配多端数据返回
1.多端内容适配
1.默认规则
- springboot多端内容适配
- 基于请求头内容协商(默认开启)
- 客户端向服务端发送请求,携带HTTP标准的Accept请求头
- Accept:
application/json
、text/xml
、text/yaml
- 服务端根据客户端请求头期望的数据类型进行动态返回
- Accept:
- 客户端向服务端发送请求,携带HTTP标准的Accept请求头
- 基于请求参数内容协商(需要开启)
- 发送请求
GET/projects/spring-boot?format=json
- 匹配到
@GetMapping("/projects/spring-boot")
- 根据参数协商,优先返回json类型数据【需要开启参数匹配设置】
- 发送请求
- 基于请求头内容协商(默认开启)
2.效果演示
请求同一个接口,可以返回json和xml不同格式数据
-
引入支持写出xml内容依赖
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
-
标注注解
@JacksonXmlRootElement // 可以写出为xml文档 @Data public class Person { private Long id; private String userName; private String email; private Integer age; }
-
开启基于请求参数的内容协商
# 开启基于请求参数的内容协商功能。 默认参数名:format。 默认此功能不开启 spring.mvc.contentnegotiation.favor-parameter=true # 指定内容协商时使用的参数名。默认是 format spring.mvc.contentnegotiation.parameter-name=type
-
效果
3.配置协商规则可与支持类型
-
修改内容协商方式
#使用参数进行内容协商 spring.mvc.contentnegotiation.favor-parameter=true #自定义参数名,默认为format spring.mvc.contentnegotiation.parameter-name=myparam
-
大多数MediaType都是开箱即用的。也可以自定义内容类型,如:
spring.mvc.contentnegotiation.media-types.yaml=text/yaml
2.自定义内容返回
1.增加yaml返回支持
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
把对象写成yaml
public static void main(String[] args) throws JsonProcessingException {
Person person = new Person();
person.setId(1L);
person.setUserName("张三");
person.setEmail("aaa@qq.com");
person.setAge(18);
YAMLFactory factory = new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
ObjectMapper mapper = new ObjectMapper(factory);
String s = mapper.writeValueAsString(person);
System.out.println(s);
}
编写配置
#新增一种媒体类型
spring.mvc.contentnegotiation.media-types.yaml=text/yaml
增加HttpMessageConverter
组件,专门负责把对象写成yaml格式
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override //配置一个能把对象转为yaml的messageConverter
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyYamlHttpMessageConverter());
}
};
}
2.思考:如何增加其他
- 配置媒体类型支持
spring.mvc.contentnegotiation.media-types.yaml=text/yaml
- 编写对应的
HttpMessageConverter
,要告诉Boot这个支持的媒体类型- 按照3的实例
- 把MessageConverter组件加入到底层
- 容器放一个
WebMvcConfigurer
组件,并配置底层的MessageConverter
- 容器放一个
3.HttpMessageConverter的示例写法
public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
private ObjectMapper objectMapper = null; //把对象转成yaml
public MyYamlHttpMessageConverter(){
//告诉SpringBoot这个MessageConverter支持哪种媒体类型 //媒体类型
super(new MediaType("text", "yaml", Charset.forName("UTF-8")));
YAMLFactory factory = new YAMLFactory()
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
this.objectMapper = new ObjectMapper(factory);
}
@Override
protected boolean supports(Class<?> clazz) {
//只要是对象类型,不是基本类型
return true;
}
@Override //@RequestBody
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override //@ResponseBody 把对象怎么写出去
protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
//try-with写法,自动关流
try(OutputStream os = outputMessage.getBody()){
this.objectMapper.writeValue(os,methodReturnValue);
}
}
}
3.内容协商原理-HttpMessageConverter
HttpMesageConverter
怎么工作?合适工作?- 定制
HttpMessageConverter
来实现多端内容协商- 编写
WebMvcConfigurer
提供的configureMessageConverters
底层,修改底层的MessageConverter
9.最佳实战
SpringBoot款已经默认配置好了web开发场景常用功能。我们直接使用即可
三种方式
全自动 | 直接编写控制器逻辑 | 全部使用自动配置默认效果 | |
---|---|---|---|
手自一体 | @Configuration+ 配置WebMvcConfigurer +配置WebMvcRegistrations | 不要标注@EnableWebMvc | 自动配置效果 手动设置部分功能 定义mvc底层组件 |
全手动 | @Configuration+ WebMvcConfigurer | 标注 @EnableWebMvc | 禁用自动配置效果 全手动配置 |
总结:
otected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override //@ResponseBody 把对象怎么写出去
protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
//try-with写法,自动关流
try(OutputStream os = outputMessage.getBody()){
this.objectMapper.writeValue(os,methodReturnValue);
}
}
}
#### 3.内容协商原理-HttpMessageConverter
> - `HttpMesageConverter`怎么工作?合适工作?
> - 定制`HttpMessageConverter`来实现多端内容协商
> - 编写`WebMvcConfigurer`提供的`configureMessageConverters`底层,修改底层的`MessageConverter`
### 9.最佳实战
> SpringBoot款已经默认配置好了web开发场景常用功能。我们直接使用即可
三种方式
| 全自动 | 直接编写控制器逻辑 | | 全部使用自动配置默认效果 |
| -------- | ------------------------------------------------------------ | ----------------------- | ------------------------------------------------------- |
| 手自一体 | @Configuration+<br />配置WebMvcConfigurer<br />+配置WebMvcRegistrations | 不要标注@EnableWebMvc | 自动配置效果<br />手动设置部分功能<br />定义mvc底层组件 |
| 全手动 | @Configuration+<br />WebMvcConfigurer | 标注<br />@EnableWebMvc | 禁用自动配置效果<br />全手动配置 |
总结:
**给容器中写一个配置类`@Configuration`,实现WebMvcConfigurer但是不要标注@EnableWebMvc注解,实现手自一体的效果**