SpringBoot
文章目录
基础篇
-
SpringBoot官方文档说明
-
pom依赖问题:
-
将阿里云源更换为HTTPS协议源:
<mirror> <id>aliyunmaven</id> <mirrorOf>*</mirrorOf> <name>aliyunmaven</name> <url>https://maven.aliyun.com/repository/public</url> </mirror>
-
IDEA的settings中的maven中确保maven程序和库为本地安装的程序和库,在两处的vm参数添加:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true
-
IDEA中右侧maven依次从clean点击至install执行测试开始依赖下载。
-
再次mvn clean,还没消红再重启IDEA
-
-
支持的配置属性(properties):
https://docs.spring.io/spring-boot/docs/2.3.12.RELEASE/reference/html/appendix-application-properties.html#common-application-properties-actuator
-
依赖管理
-
SpringBoot场景启动器
只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
-
Spring官方启动器:
spring-boot-starter-*
: *** **就某种场景;-
SpringBoot官方所有支持的场景:
https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.build-systems.starters
-
-
第三方启动器:
*-spring-boot-starter
:第三方为我们提供的简化开发的场景启动器。
-
-
依赖版本号
-
启动器包含依赖
-
包含依赖默认版本仲裁,可以不写版本
-
如需修改默认版本号
-
查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
-
在当前项目里面重写配置
<!--如MySQL依赖--> <properties> <mysql.version>5.1.43</mysql.version> </properties>
-
-
-
引入非版本仲裁的jar,要写版本号。
-
-
-
自动配置
-
web启动器依赖会自动配置web开发所需配置
- 自动配置SpringMVC
- 引入SpringMVC全套组件
- 自动配好SpringMVC常用组件(功能)
- 自动配好Web常见功能,如:字符编码问题
- SpringBoot帮我们配置好了所有web开发的常见场景
- 自动配置SpringMVC
-
自动配置Tomcat
-
引入Tomcat依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.3.4.RELEASE</version> <scope>compile</scope> </dependency>
-
自动配置Tomcat
-
-
自动扫描默认包结构
-
主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
-
无需以前的包扫描配置
-
想要改变扫描路径,@SpringBootApplication(scanBasePackages=“包全路径”),或者@ComponentScan 指定扫描路径:
@SpringBootApplication 等同于 @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan("包全路径")
-
-
组件自动装配底层注解
-
@Configuration
与Spring中注解方式配置IoC功能类似,指定当前类是一个配置类,也是与@Bean注解配合使用。同时包含一个重要属性:
proxyBeanMethods
:代理bean的方法,即:@Configuration(proxyBeanMethods = true)
,这与Spring中的@Scope注解功能类似,有以下两种类型:- Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
- Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
- 组件依赖必须使用Full模式默认。其他默认是否Lite模式
-
@Bean
与Spring中的@Bean功能一样,配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
-
@Component、@Controller、@Service、@Repository
与Spring中的功能相同
-
@ComponentScan
与Spring中的功能相同,指定spring在创建容器时要扫描的包
-
@Import
与Spring中的功能类似,给一个配置类导入另一个配置类,给容器中自动创建出导入的组件、默认组件的名字就是全类名。属性:value,类的字节码(即xxx.class)
- @Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8
-
@Conditional
SpringBoot特有,条件装配注解。满足Conditional指定的条件,则进行组件注入
-
-
原生配置文件引入
即XML配置文件导入,使用@ImportResource注解
-
配置绑定
读取properties文件中的内容,并且把它封装到JavaBean中,以供随时使用。步骤:
- 将JavaBean引入SpringBoot容器中
- 使用@ConfigurationProperties注解,填入prefix生效
方法:
-
@Component + @ConfigurationProperties
@Component @ConfigurationProperties(prefix="xxx") ------JavaBean类定义------ ------控制器类中------ @Autowired //注入JavaBean JavaBean对象定义;
-
@EnableConfigurationProperties
@EnableConfigurationProperties ------配置类定义------
-
自动配置原理入门
见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=124
https://www.yuque.com/atguigu/springboot/
-
最佳实践
-
最佳实践
即开发SpringBoot应用的最优步骤
-
引入场景依赖
https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
-
查看自动配置了哪些(选做)
- 自己分析,引入场景对应的自动配置一般都生效了
- 配置文件中debug=true开启自动配置报告。Negative(不生效)\Positive(生效)
-
是否需要修改
- 参照文档修改配置项
- https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties
- 自己分析。xxxxProperties绑定了配置文件的哪些。
- 参照文档修改配置项
-
自定义加入或者替换组件
- @Bean、@Component。。。
-
自定义器 XXXXXCustomizer;
-
…
-
开发小技巧
-
开发小技巧
-
Lombok
-
功能1:简化JavaBean开发
步骤:
-
导入依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
-
IDEA安装lombok插件
Settings→plugins→marketplace,搜索lombok安装
-
JavaBean类上,
-
get/set方法:@Date注解
-
toString方法:@ToString注解
-
equals&hashcode方法:@EqualsAndHashCode注解
-
构造器:
-
无参构造器:@NoArgsConstructor注解
-
有参构造:
-
单独JavaBean时:直接使用@AllArgsConstructor注解
-
包含其他JavaBean时:自定义除其他JavaBean外的全部参数的构造方法,如下:
@NoArgsConstructor //@AllArgsConstructor @Data @ToString @EqualsAndHashCode public class User { private String name; private Integer age; private Pet pet; public User(String name,Integer age){ this.name = name; this.age = age; } }
-
-
-
-
-
功能2:简化日志开发
步骤:
-
控制器类上添加@Slf4j
-
类方法中根据逻辑添加响应功能,如:
log.info("请求进来了....");
-
-
-
dev-tools
功能:项目热更新,即项目修改或更新后不需要重新启动项目
步骤:
-
加载依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
-
项目或者页面修改以后:Ctrl+F9;
实质:后端代码变化后就是一个SpringBoot应用的重启过程,但是前端静态页面更新时则是重新部署
真正的热更新:
- 付费插件:JRebel
-
-
Spring Initailizr(项目初始化向导)
功能:Idea中快速创建SpringBoot项目的初始化向导,能自动依赖引入,自动创建项目结构,自动编写好主配置类等。
步骤:
-
new project页面选择Spring Initializr,声明组织和项目名,next,
-
选择我们需要的开发场景
如:web、mybatis、Redis等,next
-
确认
注意:
项目结构说明
-
-
核心篇
Yaml
-
yaml
-
简介:YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。
- 特点:非常适合用来做以数据为中心的配置文件
-
基本语法
-
key: value;kv之间有空格
-
大小写敏感
-
使用缩进表示层级关系
-
缩进不允许使用tab,只允许空格
-
缩进的空格数不重要,只要相同层级的元素左对齐即可
-
'#'表示注释
-
字符串无需加引号
- 如果要加,
- 单引号’’ ,表示字符串内容会被转义,即原格式输出,如:’\n’输出为\n而不是换行;
- 双引号"" ,表示字符串内容不会被转义,即原含义输出,如:’\n’输出为换行;
- 如果要加,
-
-
数据类型
- 字面量:单个的、不可再分的值。date、boolean、string、number、null
k: v
- 对象:键值对的集合。map、hash、set、object
行内写法: k: {k1:v1,k2:v2,k3:v3} #或 k: k1: v1 k2: v2 k3: v3
- 数组:一组按次序排列的值。array、list、queue
行内写法: k: [v1,v2,v3] #或者 k: - v1 - v2 - v3
-
示例
# yaml表示以上对象 person: userName: zhangsan boss: false birth: 2019/12/12 20:12:33 age: 18 pet: name: tomcat weight: 23.4 interests: [篮球,游泳] animal: - jerry - mario score: english: first: 30 second: 40 third: 50 math: [131,140,148] chinese: {first: 128,second: 136} salarys: [3999,4999.98,5999.99] allPets: sick: - {name: tom} - {name: jerry,weight: 47} health: [{name: mario,weight: 47}]
-
-
配置提示
自定义的类和配置文件绑定一般没有提示。
方法:引入依赖即可,且为保证Jar包大小和部署项目效率,配置mvn打包时排除该依赖包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build>
Web开发
-
Web开发
-
SpringMVC自动配置概览:见语雀尚硅谷笔记
-
静态资源访问
-
静态资源目录:
SpringBoot拥有且支持的静态资源目录有:
/static
(or/public
or/resources
or/META-INF/resources
,且必须是在类路径下,默认只创建\static
目录- 原理: 静态映射/**。
- 请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面
改变默认的静态资源路径:
#增加静态资源目录 spring: resources: static-locations: [classpath:/haha/]
-
静态资源访问前缀
默认无前缀
#配置所有静态资源目录下的资源都在该映射下 spring: mvc: static-path-pattern: /res/**
当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找
-
webjar
简介:WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。
自动映射 /webjars/**
https://www.webjars.org/方法:
-
加入依赖
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.5.1</version> </dependency>
-
使用:
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
或在静态页面中使用该地址引入。
-
-
-
欢迎页支持
两种方式:
-
静态资源路径下 index.html
- 可以配置静态资源路径
- 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
spring: # mvc: # static-path-pattern: /res/** 这个会导致welcome page功能失效 resources: static-locations: [classpath:/haha/]
-
controller能处理/index
-
-
自定义 Favicon
即浏览器标签页图标自定义
favicon.ico 放在静态资源目录下即可
spring: # mvc: # static-path-pattern: /res/** 这个会导致 Favicon 功能失效
-
静态资源配置原理:
见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=136
https://www.yuque.com/atguigu/springboot/
-
请求处理
-
Restful风格请求映射
-
简介和使用
-
简介:Rest风格支持(使用HTTP请求方式动词来表示对资源的操作)
-
特性
-
以前的映射命名方式:/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户
-
Restful方式:统一使用/user映射, 请求发送和接收处代码区别:GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户
-
-
使用支持:开启核心Filter:HiddenHttpMethodFilter
-
用法:
-
前端代码:表单method=post,添加隐藏域 _method=put/delete
<form action="/user" method="post"> <input name="_method" type="hidden" value="PUT/DELETE"> <input value="REST PUT/DELETE 提交" type="submit"> </form>
-
SpringBoot中手动开启,yaml配置文件配置
mvc: hiddenmethod: filter: enabled: true
-
为什么要手动开启
//源码 @Bean @ConditionalOnMissingBean(HiddenHttpMethodFilter.class) @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false) public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() { return new OrderedHiddenHttpMethodFilter(); }
-
扩展:如何把_method 这个名字换成我们自己喜欢的。
//自定义filter @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter(){ HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); methodFilter.setMethodParam("_m"); return methodFilter; }
-
-
-
-
-
原理
- 表单提交会带上**_method=PUT**
- 请求过来被HiddenHttpMethodFilter拦截
- 请求是否正常,并且是POST
- 获取到**_method**的值。
- 兼容以下请求;PUT.DELETE.PATCH
- 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
- 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。
- 请求是否正常,并且是POST
-
Rest使用客户端工具,
- 如PostMan直接发送Put、delete等方式请求,无需Filter。
-
-
请求映射原理
SpringMVC功能分析都从 org.springframework.web.servlet.DispatcherServlet-》doDispatch()
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=139
https://www.yuque.com/atguigu/springboot/
-
常用注解
@PathVariable路径变量、
@RequestHeader获取请求头、
@RequestParam获取请求参数、
@CookieValue获取cookie值、
@RequestBody获取请求体(POST)、
@RequestAttribute获取request域属性、
@MatrixVariable矩阵变量(不太重要)
-
矩阵变量功能:
-
类似于@RequestParam获取请求参数的查询字符串功能,用于参数获取
- url写法(表示法):
/xxx;xx=x;xx=x,x,x
- url写法(表示法):
-
页面开发中,cookie被禁用了,session的另一种使用方式:
- session原理:session.set(a,b) —> jsessionid —> cookie —> 每次发请求携带 //cookie被禁用,jsessionid就无法获取
替换方法:url重写:/xxx;jsessionid=xxx //把cookie的值用矩阵变量的方式进行传递
-
-
使用方法:
SpringBoot默认是禁用了矩阵变量的功能
手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
removeSemicolonContent(移除分号内容)支持矩阵变量的
- 注:矩阵变量必须有url路径变量才能被解析
-
-
常用注解源码分析
具体见雷大神视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=143
-
请求参数传入解析原理(没看)
以下见雷大神语雀笔记https://www.yuque.com/atguigu/springboot/,总原理过程:语雀5.3.3,贯穿视频p145和146
-
Servlet API参数解析原理https://www.bilibili.com/video/BV1Et411Y7tQ?p=144,语雀5.3.1.2
-
Map、Model复杂参数解析原理(map、model里面的数据会被放在request的请求域 =调用了request.setAttribute)https://www.bilibili.com/video/BV1Et411Y7tQ?p=145,语雀5.3.1.3
-
以上两类参数共性
Map<String,Object> map, Model model, HttpServletRequest request 都是可以给request域中放数据, request.getAttribute();
-
-
自定义类型参数解析原理,如封装POJOhttps://www.bilibili.com/video/BV1Et411Y7tQ?p=146,语雀5.3.1.4
-
自定义converter参数解析原理,如前端自定义规则传参解析https://www.bilibili.com/video/BV1Et411Y7tQ?p=147,无笔记(不重要)
-
-
-
响应处理
-
jackson.jar+@ResponseBody
返回响应数据
用法:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> web场景自动引入了json场景 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <version>2.3.4.RELEASE</version> <scope>compile</scope> </dependency>
原理:
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=148
https://www.bilibili.com/video/BV1Et411Y7tQ?p=149
https://www.yuque.com/atguigu/springboot/
-
重要总结
SpringMVC到底支持哪些返回值
ModelAndView Model View ResponseEntity ResponseBodyEmitter StreamingResponseBody HttpEntity HttpHeaders Callable DeferredResult ListenableFuture CompletionStage WebAsyncTask 有 @ModelAttribute 且为对象类型的 @ResponseBody 注解 ---> RequestResponseBodyMethodProcessor;
实现多协议数据兼容。json、xml、x-guigu
0、@ResponseBody 响应数据出去 调用 RequestResponseBodyMethodProcessor 处理
1、Processor 处理方法返回值。通过 MessageConverter 处理
2、所有 MessageConverter 合起来可以支持各种媒体类型数据的操作(读、写)
3、内容协商找到最终的 messageConverter;
-
HTTPMessageConverter原理
为返回响应数据原理的一部分,从p149的13分钟开始。
简介:HttpMessageConverter: 看是否支持将 此 Class类型的对象,转为MediaType类型的数据。
例子:Person对象转为JSON。或者 JSON转为Person
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=149
https://www.yuque.com/atguigu/springboot/
-
-
内容协商
-
功能:根据客户端接收能力不同,返回不同媒体类型的数据。
-
使用方法:引入XML依赖
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
-
postman分别测试返回json和xml
只需要改变请求头中Accept字段。Http协议中规定的,告诉服务器本客户端可以接收的数据类型。
-
开启基于请求参数的内容协商功能
为了方便内容协商,开启浏览器参数方式内容协商功能。
https://www.bilibili.com/video/BV1Et411Y7tQ?p=151
spring: contentnegotiation: favor-parameter: true #开启请求参数内容协商模式
发请求:
http://localhost:8080/test/person?format=json
http://localhost:8080/test/person?format=xml
确定客户端接收什么样的内容类型;
1、Parameter策略优先确定是要返回json数据(获取请求头中的format的值)
2、最终进行内容协商返回给客户端json即可。
-
原理
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=150
https://www.yuque.com/atguigu/springboot/
-
自定义 MessageConverter
不太重要。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=151
https://www.bilibili.com/video/BV1Et411Y7tQ?p=152
https://www.yuque.com/atguigu/springboot/
-
注意:
有可能我们添加的自定义的功能会覆盖默认很多功能,导致一些默认的功能失效。
大家考虑,上述功能除了我们完全自定义外?SpringBoot有没有为我们提供基于配置文件的快速修改媒体类型功能?怎么配置呢?【提示:参照SpringBoot官方文档web开发内容协商章节】
-
-
-
-
视图解析与模板引擎(略)
-
视图解析原理
SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染
不太重要。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=158
https://www.yuque.com/atguigu/springboot/
-
模板引擎-典型:thymeleaf
不太重要。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=154
https://www.yuque.com/atguigu/springboot/
-
-
构建后台管理系统
有经验,不太重要。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=158
https://www.yuque.com/atguigu/springboot/
-
拦截器
步骤:(可集成日记组件)
-
编写一个拦截器实现HandlerInterceptor接口
//登录拦截举例 @Slf4j public class LoginInterceptor implements HandlerInterceptor { /** * 目标方法执行之前 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestURI = request.getRequestURI(); log.info("preHandle拦截的请求路径是{}",requestURI); //登录检查逻辑 HttpSession session = request.getSession(); Object loginUser = session.getAttribute("loginUser"); if(loginUser != null){ //放行 return true; } //拦截住。未登录。跳转到登录页 request.setAttribute("msg","请先登录"); // re.sendRedirect("/"); request.getRequestDispatcher("/").forward(request,response); return false; } /** * 目标方法执行完成以后 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("postHandle执行{}",modelAndView); } /** * 页面渲染以后 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("afterCompletion执行异常{}",ex); } }
-
拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
-
指定拦截规则【如果是拦截所有,静态资源也会被拦截】
@Configuration public class AdminWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**") //所有请求都被拦截包括静态资源 .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求 } }
原理:
暂时不看。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=160
https://www.yuque.com/atguigu/springboot/
-
-
文件上传
步骤:
-
前端:
<form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="submit" value="提交"> </form>
-
后端:
/** * MultipartFile 自动封装上传过来的文件 * @param email * @param username * @param headerImg * @param photos * @return */ @PostMapping("/upload") public String upload(@RequestParam("email") String email, @RequestParam("username") String username, @RequestPart("headerImg") MultipartFile headerImg, @RequestPart("photos") MultipartFile[] photos) throws IOException { log.info("上传的信息:email={},username={},headerImg={},photos={}", email,username,headerImg.getSize(),photos.length); if(!headerImg.isEmpty()){ //保存到文件服务器,OSS服务器 String originalFilename = headerImg.getOriginalFilename(); headerImg.transferTo(new File("H:\\cache\\"+originalFilename)); } if(photos.length > 0){ for (MultipartFile photo : photos) { if(!photo.isEmpty()){ String originalFilename = photo.getOriginalFilename(); photo.transferTo(new File("H:\\cache\\"+originalFilename)); } } } return "main"; }
原理:
暂时不看。具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=162
https://www.yuque.com/atguigu/springboot/
-
-
异常错误处理
-
默认规则
-
默认情况下,Spring Boot提供
/error
处理所有错误的映射 -
对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
-
客户端,如postman
json数据
-
网页端
空白页
-
-
-
自定义规则
-
要对其进行自定义,添加
View
解析为error
-
要完全替换默认行为,可以实现
ErrorController
并注册该类型的Bean定义,或添加ErrorAttributes类型的组件
以使用现有机制但替换其内容。 -
error/下的4xx,5xx页面会被自动解析;
-
-
原理:
暂时不看。具体见雷大神的语雀笔记和视频
https://www.yuque.com/atguigu/springboot/
-
定制错误处理逻辑
https://www.bilibili.com/video/BV1Et411Y7tQ?p=164
-
异常处理自动配置原理
https://www.bilibili.com/video/BV1Et411Y7tQ?p=165
-
异常处理步骤流程
https://www.bilibili.com/video/BV1Et411Y7tQ?p=166
-
-
-
Web原生组件注入(Servlet、Filter、Listener)
官方文档在https://docs.spring.io/spring-boot/docs/2.3.12.RELEASE/reference/html/spring-boot-features.html#boot-features-embedded-container,7.4.1及7.4.2章节,不太重要
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=167
https://www.yuque.com/atguigu/springboot/
原理:
暂时不看,具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=168
https://www.yuque.com/atguigu/springboot/
-
嵌入式Servlet容器
官方文档在https://docs.spring.io/spring-boot/docs/2.3.12.RELEASE/reference/html/spring-boot-features.html#boot-features-embedded-container,7.4.3章节,不太重要
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=169
https://www.yuque.com/atguigu/springboot/
-
Web开发定制化原理总结
重要总结
-
原理分析套路
场景starter - xxxxAutoConfiguration - 导入xxx组件 - 绑定xxxProperties – 绑定配置文件项
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=170
https://www.yuque.com/atguigu/springboot/
-
-
数据访问
-
数据访问
-
JDBC
暂时不看,具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=171
https://www.yuque.com/atguigu/springboot/
-
Druid
-
自定义方式
暂时不看,具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=172
https://www.yuque.com/atguigu/springboot/
-
starter自动方式
暂时不看,具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=173
https://www.yuque.com/atguigu/springboot/
-
-
Mybatis
-
方法步骤
-
导入mybatis官方starter
-
编写mapper接口。标注@Mapper注解
- 可以在MainApplication主程序类中添加
@MapperScan("Mapper包全限定类名")
简化,其他的接口就可以不用标注@Mapper
注解
- 可以在MainApplication主程序类中添加
-
绑定mapper接口
- XML方式:编写sql映射文件并绑定mapper接口
- 注解方式:接口方法上方添加SQL注解即可
- 混合方式:以上两种方式均包含
- 简单方法直接注解方式
- 复杂方法编写mapper.xml进行绑定映射
-
在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration)
-
-
导入tarter启动器:https://github.com/mybatis
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
-
使用Spring Initializr更快
-
starter中的内容:
-
starter加载的重要组件
-
全局配置文件
-
SqlSessionFactory: 自动配置好了
-
SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
-
@Import(AutoConfiguredMapperScannerRegistrar.class);
-
Mapper: 只要我们写的操作MyBatis的接口标准了 @Mapper 就会被自动扫描进来
@EnableConfigurationProperties(MybatisProperties.class)//MyBatis配置项绑定类。 @AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class }) public class MybatisAutoConfiguration{} @ConfigurationProperties(prefix = "mybatis") public class MybatisProperties
-
-
-
配置整合配置文件
-
配置mybatis规则
即全局配置信息
步骤或内容:
-
全局配置规则(以下均为XML模式绑定Mapper)
-
全局配置文件方式:
SpringBoot配置文件中添加:
mybatis: config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置 mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
mybatis-config.xml 全局配置文件内容
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!--configuration中内容可变可省--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
-
SpringBoot的configuration配置类方式
配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值
SpringBoot配置文件中添加:
# 配置mybatis规则 mybatis: mapper-locations: classpath:mybatis/mapper/*.xml configuration: map-underscore-to-camel-case: true #其他配置也在这里添加
所有配置如下:
https://mybatis.org/mybatis-3/zh/configuration.html#settings
-
-
-
Mapper绑定方式:
-
XML方式
-
编写sql映射文件xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.admin.mapper.AccountMapper"> <!-- public Account getAcct(Long id); --> <select id="getAcct" resultType="com.atguigu.admin.bean.Account"> select * from account_tbl where id=#{id} </select> </mapper>
-
yaml中指定xml位置
上述已经展示,即
mapper-locations
属性
-
-
注解方式
- 接口方法上方添加SQL注解即可。
-
混合模式
- 以上两种方式都存在即是混合模式
-
扩展:insert方法中自增主键获得(返回):
-
xml方式
开启useGeneratedKeys和keyProperty属性,然后通过resultType或resultMap指定的对象获取即可。
<insert id=”insertUser” useGeneratedKeys=”true” keyProperty=”userId” ></insert>
-
注解方式
使用@Options注解
-
-
-
-
Mybatis-Plus
-
简介
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官网:https://mp.baomidou.com/guide/install.html
建议安装 MybatisX 插件
-
整合mybatis-plus
配置启动器依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency>
-
启动器自动配置内容
-
MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对****mybatis-plus的定制
-
SqlSessionFactory 自动配置好。底层是容器中默认的数据源
-
**mapperLocations 自动配置好的。有默认值。*classpath*:/mapper/*/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
-
容器中也自动配置好了 SqlSessionTemplate
-
@Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan(“com.atguigu.admin.mapper”) 批量扫描就行
-
-
-
优势
- 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力
- 业务层接口继承IService类,实现类继承ServiceImpl类即可快速完成业务层开发
-
实例demo(还没看)
https://www.bilibili.com/video/BV1Et411Y7tQ?p=177,查询
https://www.bilibili.com/video/BV1Et411Y7tQ?p=178,分页
- Mybatis-plus分页插件:需要新建一个Configuration类,类中配置一个分类拦截器
https://www.bilibili.com/video/BV1Et411Y7tQ?p=179,删除
-
-
-
Redis
- Redis
Junit5
-
Junit5
Spring Boot 2.2.0 版本开始引入 JUnit 5 作为单元测试默认库
作为最新版本的JUnit框架,JUnit5与之前版本的Junit框架有很大的不同。由三个不同子项目的几个不同模块组成。
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
-
JUnit Platform: Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
-
JUnit Jupiter: JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部 包含了一个测试引擎,用于在Junit Platform上运行。
-
JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x,Junit3.x的测试引擎。
-
注意:SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test**)**
-
继续使用:方法:需要自行引入vintage
<dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency>
-
-
自动配置
使用Spring Initializr自动创建SpringBoot项目后,会自动引入Junit5的Starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
引入后自动配置,配置内容如下:
-
4→5使用方式变化
- Junit4使用:类上方:
@SpringBootTest + @RunWith(SpringApplication.class)
- Junit5使用:类上方只需要:
SpringBootTest
- SpringBoot整合Junit以后。
- 编写测试方法:@Test标注(注意需要使用junit5版本的注解)
- Junit类具有Spring的功能,@Autowired、比如 @Transactional 标注测试方法,测试完成后自动回滚
- SpringBoot整合Junit以后。
- Junit4使用:类上方:
-
官方文档
JUnit5的注解与JUnit4的注解有所变化
https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
-
Junit5常用注解
-
**@Test 😗*表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
-
**@ParameterizedTest 😗*表示方法是参数化测试,下方会有详细介绍
-
**@RepeatedTest 😗*表示方法可重复执行,下方会有详细介绍
-
**@DisplayName 😗*为测试类或者测试方法设置展示名称
-
**@BeforeEach 😗*表示在每个单元测试之前执行
-
**@AfterEach 😗*表示在每个单元测试之后执行
-
**@BeforeAll 😗*表示在所有单元测试之前执行,默认要求声明为静态方法
-
**@AfterAll 😗*表示在所有单元测试之后执行,默认要求声明为静态方法
-
**@Tag 😗*表示单元测试类别,类似于JUnit4中的@Categories
-
**@Disabled 😗*表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
-
**@Timeout 😗*表示测试方法运行如果超过了指定时间将会返回错误
-
**@ExtendWith 😗*为测试类或测试方法提供扩展类引用
-
-
Junit5断言
断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。且前一个断言方法失败后,后一个断言方法就不会执行。断言方法JUnit 5 内置的断言可以分成如下几个类别:
检查业务逻辑返回的数据是否合理。
所有的测试运行结束以后,会有一个详细的测试报告;
-
简单断言
用来对单个值进行简单的验证。如:
方法 说明 assertEquals 判断两个对象或两个原始类型是否相等 assertNotEquals 判断两个对象或两个原始类型是否不相等 assertSame 判断两个对象引用是否指向同一个对象 assertNotSame 判断两个对象引用是否指向不同的对象 assertTrue 判断给定的布尔值是否为 true assertFalse 判断给定的布尔值是否为 false assertNull 判断给定的对象引用是否为 null assertNotNull 判断给定的对象引用是否不为 null -
数组断言
通过 assertArrayEquals 方法来判断两个对象或原始类型的数组是否相等
@Test @DisplayName("array assertion") public void array() { assertArrayEquals(new int[]{1, 2}, new int[] {1, 2}); }
-
组合断言
assertAll 方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言
组合中所有断言都需要成功;
@Test @DisplayName("assert all") public void all() { assertAll("Math", () -> assertEquals(2, 1 + 1), () -> assertTrue(1 > 0) ); }
-
异常断言
在JUnit4时期,想要测试方法的异常情况时,需要用**@Rule注解的ExpectedException变量还是比较麻烦的。而JUnit5提供了一种新的断言方式Assertions.assertThrows()** ,配合函数式编程就可以进行使用。
@Test @DisplayName("异常测试") public void exceptionTest() { ArithmeticException exception = Assertions.assertThrows( //扔出断言异常 ArithmeticException.class, () -> System.out.println(1 % 0)); }
-
超时断言
unit5还提供了Assertions.assertTimeout() 为测试方法设置了超时时间
@Test @DisplayName("超时测试") public void timeoutTest() { //如果测试方法时间超过1s将会异常 Assertions.assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(500)); }
-
快速失败
通过 fail 方法直接使得测试失败
@Test @DisplayName("fail") public void shouldFail() { fail("This should fail"); }
-
-
Junit5前置条件
也叫假设。JUnit 5 中的前置条件(assumptions【假设】)类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法的执行终止。前置条件可以看成是测试方法执行的前提,当该前提不满足时,就没有继续执行的必要。Junit运行日志中不通过显示跳过,而断言失败则为失败。
@DisplayName("前置条件") public class AssumptionsTest { private final String environment = "DEV"; @Test @DisplayName("simple") public void simpleAssume() { assumeTrue(Objects.equals(this.environment, "DEV")); assumeFalse(() -> Objects.equals(this.environment, "PROD")); } @Test @DisplayName("assume then do") public void assumeThenDo() { assumingThat( Objects.equals(this.environment, "DEV"), () -> System.out.println("In DEV") ); } }
assumeTrue 和 assumFalse 确保给定的条件为 true 或 false,不满足条件会使得测试执行终止。assumingThat 的参数是表示条件的布尔值和对应的 Executable 接口的实现对象。只有条件满足时,Executable 对象才会被执行;当条件不满足时,测试执行并不会终止。
-
Junit5嵌套测试
JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach 和@AfterEach 注解,而且嵌套的层次没有限制。注意:内层测试可以驱动外层测试,而外层测试不能驱动内层测试。
@DisplayName("A stack") class TestingAStackDemo { Stack<Object> stack; @Test @DisplayName("is instantiated with new Stack()") void isInstantiatedWithNew() { new Stack<>(); } @Nested @DisplayName("when new") class WhenNew { @BeforeEach void createNewStack() { stack = new Stack<>(); } @Test @DisplayName("is empty") void isEmpty() { assertTrue(stack.isEmpty()); } @Test @DisplayName("throws EmptyStackException when popped") void throwsExceptionWhenPopped() { assertThrows(EmptyStackException.class, stack::pop); } @Test @DisplayName("throws EmptyStackException when peeked") void throwsExceptionWhenPeeked() { assertThrows(EmptyStackException.class, stack::peek); } @Nested @DisplayName("after pushing an element") class AfterPushing { String anElement = "an element"; @BeforeEach void pushAnElement() { stack.push(anElement); } @Test @DisplayName("it is no longer empty") void isNotEmpty() { assertFalse(stack.isEmpty()); } @Test @DisplayName("returns the element when popped and is empty") void returnElementWhenPopped() { assertEquals(anElement, stack.pop()); assertTrue(stack.isEmpty()); } @Test @DisplayName("returns the element when peeked but remains not empty") void returnElementWhenPeeked() { assertEquals(anElement, stack.peek()); assertFalse(stack.isEmpty()); } } } }
-
Junit5参数化测试
参数化测试是JUnit5很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。
利用**@ValueSource**等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。
@ValueSource: 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型
@NullSource: 表示为参数化测试提供一个null的入参
@EnumSource: 表示为参数化测试提供一个枚举入参
@CsvFileSource:表示读取指定CSV文件内容作为参数化测试入参
@MethodSource:表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)
当然如果参数化测试仅仅只能做到指定普通的入参还达不到让我觉得惊艳的地步。让我真正感到他的强大之处的地方在于他可以支持外部的各类入参。如:CSV,YML,JSON 文件甚至方法的返回值也可以作为入参。只需要去实现ArgumentsProvider接口,任何外部文件都可以作为它的入参。
@ParameterizedTest @ValueSource(strings = {"one", "two", "three"}) @DisplayName("参数化测试1") public void parameterizedTest1(String string) { System.out.println(string); Assertions.assertTrue(StringUtils.isNotBlank(string)); } @ParameterizedTest @MethodSource("method") //指定方法名 @DisplayName("方法来源参数") public void testWithExplicitLocalMethodSource(String name) { System.out.println(name); Assertions.assertNotNull(name); } static Stream<String> method() { return Stream.of("apple", "banana"); }
-
迁移指南
Junit5之前版本的单元测试方法迁移变为Junit5测试的指南:
在进行迁移的时候需要注意如下的变化:
-
注解在 org.junit.jupiter.api 包中,断言在 org.junit.jupiter.api.Assertions 类中,前置条件在 org.junit.jupiter.api.Assumptions 类中。
-
把@Before 和@After 替换成@BeforeEach 和@AfterEach。
-
把@BeforeClass 和@AfterClass 替换成@BeforeAll 和@AfterAll。
-
把@Ignore 替换成@Disabled。
-
把@Category 替换成@Tag。
-
把@RunWith、@Rule 和@ClassRule 替换成@ExtendWith。
-
-
指标监控
-
指标监控
Spring Actuator
-
未来每一个微服务在云上部署以后,我们都需要对其进行监控、追踪、审计、控制等。SpringBoot就抽取了Actuator场景,使得我们每个微服务快速引用即可获得生产级别的应用监控、审计等功能。
-
1.x与2.x的不同
-
如何使用
-
引入场景
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
-
引入的内容
-
-
访问 http://localhost:8080/actuator/**
-
暴露所有监控信息为HTTP
management: endpoints: enabled-by-default: true #暴露所有端点信息 web: exposure: include: '*' #以web方式暴露
-
测试
http://localhost:8080/actuator/beans
http://localhost:8080/actuator/configprops
http://localhost:8080/actuator/metrics
http://localhost:8080/actuator/metrics/jvm.gc.pause
http://localhost:8080/actuator/endpointName/detailPath
。。。。。。
-
-
可视化
https://github.com/codecentric/spring-boot-admin指导文档:https://codecentric.github.io/spring-boot-admin/2.3.1/
视频:https://www.bilibili.com/video/BV1Et411Y7tQ?p=191
-
Actuator Endpoint
端点。
常使用的端点如下:
ID 描述 auditevents
暴露当前应用程序的审核事件信息。需要一个 AuditEventRepository组件
。beans
显示应用程序中所有Spring Bean的完整列表。 caches
暴露可用的缓存。 conditions
显示自动配置的所有条件信息,包括匹配或不匹配的原因。 configprops
显示所有 @ConfigurationProperties
。env
暴露Spring的属性 ConfigurableEnvironment
flyway
显示已应用的所有Flyway数据库迁移。 需要一个或多个 Flyway
组件。health
显示应用程序运行状况信息。 httptrace
显示HTTP跟踪信息(默认情况下,最近100个HTTP请求-响应)。需要一个 HttpTraceRepository
组件。info
显示应用程序信息。 integrationgraph
显示Spring integrationgraph
。需要依赖spring-integration-core
。loggers
显示和修改应用程序中日志的配置。 liquibase
显示已应用的所有Liquibase数据库迁移。需要一个或多个 Liquibase
组件。metrics
显示当前应用程序的“指标”信息。 mappings
显示所有 @RequestMapping
路径列表。scheduledtasks
显示应用程序中的计划任务。 sessions
允许从Spring Session支持的会话存储中检索和删除用户会话。需要使用Spring Session的基于Servlet的Web应用程序。 shutdown
使应用程序正常关闭。默认禁用。 startup
显示由 ApplicationStartup
收集的启动步骤数据。需要使用SpringApplication
进行配置BufferingApplicationStartup
。threaddump
执行线程转储。 如果您的应用程序是Web应用程序(Spring MVC,Spring WebFlux或Jersey),则可以使用以下附加端点:
ID 描述 heapdump
返回 hprof
堆转储文件。jolokia
通过HTTP暴露JMX bean(需要引入Jolokia,不适用于WebFlux)。需要引入依赖 jolokia-core
。logfile
返回日志文件的内容(如果已设置 logging.file.name
或logging.file.path
属性)。支持使用HTTPRange
标头来检索部分日志文件的内容。prometheus
以Prometheus服务器可以抓取的格式公开指标。需要依赖 micrometer-registry-prometheus
。最常用的Endpoint
-
Health:监控状况
健康检查端点,我们一般用于在云平台,平台会定时的检查应用的健康状况,我们就需要Health Endpoint可以为平台返回当前应用的一系列组件健康状况的集合。
重要的几点:
-
health endpoint返回的结果,应该是一系列健康检查后的一个汇总报告
-
很多的健康检查默认已经自动配置好了,比如:数据库、redis等
-
可以很容易的添加自定义的健康检查机制
-
-
Metrics:运行时指标
提供详细的、层级的、空间指标信息,这些信息可以被pull(主动推送)或者push(被动获取)方式得到;
-
通过Metrics对接多种监控系统
-
简化核心Metrics开发
-
添加自定义Metrics或者扩展已有Metrics
-
-
Loggers:日志记录
-
-
管理Endpoints
-
开启与禁用Endpoints
- 默认所有的Endpoint除过shutdown都是开启的。
- 需要开启或者禁用某个Endpoint。配置模式为 management.endpoint..enabled = true
management: endpoint: beans: enabled: true
- 或者禁用所有的Endpoint然后手动开启指定的Endpoint
management: endpoints: enabled-by-default: false endpoint: beans: enabled: true health: enabled: true
-
暴露Endpoints
支持的暴露方式
-
HTTP:默认只暴露health和info Endpoint
-
JMX:默认暴露所有Endpoint
-
除过health和info,剩下的Endpoint都应该进行保护访问。如果引入SpringSecurity,则会默认配置安全访问规则
ID JMX Web auditevents
Yes No beans
Yes No caches
Yes No conditions
Yes No configprops
Yes No env
Yes No flyway
Yes No health
Yes Yes heapdump
N/A No httptrace
Yes No info
Yes Yes integrationgraph
Yes No jolokia
N/A No logfile
N/A No loggers
Yes No liquibase
Yes No metrics
Yes No mappings
Yes No prometheus
N/A No scheduledtasks
Yes No sessions
Yes No shutdown
Yes No startup
Yes No threaddump
Yes No -
-
-
定制 Endpoint
略。见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=190
https://www.yuque.com/atguigu/springboot/
-
高级特性
-
Profile功能
快速环境切换。官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.profiles
-
application-profile功能
-
默认配置文件 application.yaml;任何时候都会加载
-
指定环境配置文件 application-{env}.yaml
-
激活指定环境
-
配置文件激活
-
命令行激活:
java -jar xxx.jar --spring.profiles.active=prod --person.name=haha
- 修改配置文件的任意值,命令行优先
-
-
生效:
- 默认配置与环境配置同时生效
- 同名配置项,profile配置优先
-
-
@Profile条件装配功能
指定不同环境下生效的配置类和Bean,以下为配置类,同时可以在类中方法上添加。
@Configuration(proxyBeanMethods = false) @Profile("production") public class ProductionConfiguration { // ... }
-
profile分组
Spring Boot 允许定义配置文件组。配置文件组允许为相关的配置文件组定义逻辑名称。定义后使用我们的应用程序
--spring.profiles.active=production
来激活production
,proddb
和prodmq
配置文件。即组内所有配置文件spring.profiles.group.production[0]=proddb spring.profiles.group.production[1]=prodmq
-
-
外部化配置
官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config
简介:Spring Boot 允许您将配置外部化,以便您可以在不同环境中使用相同的应用程序代码。您可以使用各种外部配置源,包括 Java 属性文件、YAML 文件、环境变量和命令行参数(常用)。
-
所有的外部配置
Spring Boot 使用一个非常特殊的
PropertySource
顺序,旨在允许合理地覆盖值。属性按以下顺序考虑(较后项目的值覆盖较前的项目):- Default properties (specified by setting
SpringApplication.setDefaultProperties
). @PropertySource
annotations on your@Configuration
classes. Please note that such property sources are not added to theEnvironment
until the application context is being refreshed. This is too late to configure certain properties such aslogging.*
andspring.main.*
which are read before refresh begins.- Config data (such as
application.properties
files) - A
RandomValuePropertySource
that has properties only inrandom.*
. - OS environment variables.
- Java System properties (
System.getProperties()
). - JNDI attributes from
java:comp/env
. ServletContext
init parameters.ServletConfig
init parameters.- Properties from
SPRING_APPLICATION_JSON
(inline JSON embedded in an environment variable or system property). - Command line arguments.
properties
attribute on your tests. Available on@SpringBootTest
and the test annotations for testing a particular slice of your application.@TestPropertySource
annotations on your tests.- Devtools global settings properties in the
$HOME/.config/spring-boot
directory when devtools is active.
- 可见官方文档翻译
- Default properties (specified by setting
-
配置文件查找位置
(1) classpath 根路径
(2) classpath 根路径下config目录
(3) jar包当前目录
(4) jar包当前目录的config目录
(5) /config子目录的直接子目录(Linux环境)
-
配置文件加载顺序:(后面覆盖前面)
-
当前jar包内部的application.properties和application.yml
-
当前jar包内部的application-{profile}.properties 和 application-{profile}.yml
-
引用的外部jar包的application.properties和application.yml
-
引用的外部jar包的application-{profile}.properties 和 application-{profile}.yml
-
-
总顺序:
指定环境优先,外部优先,后面的可以覆盖前面的同名配置项
-
-
自定义starter
-
starter启动原理
- starter-pom引入 autoconfigurer 包
-
autoconfigure包中配置使用 META-INF/spring.factories 中 EnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
-
编写自动配置类 xxxAutoConfiguration -> xxxxProperties
-
@Configuration
-
@Conditional
-
@EnableConfigurationProperties
-
@Bean
-
…
引入starter — xxxAutoConfiguration — 容器中放入组件 ---- 绑定xxxProperties ---- 配置项
-
自定义starter
atguigu-hello-spring-boot-starter(启动器)
atguigu-hello-spring-boot-starter-autoconfigure(自动配置包)
-
配置步骤
主要根据视频学习流程:https://www.bilibili.com/video/BV1Et411Y7tQ?p=194
-
SpringBoot原理
-
SpringApplication创建初始化流程
-
SpringBoot完整启动过程
-
自定义监听组件
具体见雷大神的语雀笔记和视频
https://www.bilibili.com/video/BV1Et411Y7tQ?p=195
https://www.bilibili.com/video/BV1Et411Y7tQ?p=196
https://www.bilibili.com/video/BV1Et411Y7tQ?p=197
https://www.yuque.com/atguigu/springboot/