87.【SpringBoot-01】
SpringBoot
- (一)、前面回顾
- 1.什么是Spring
- 2.Spring 是如何简化Java开发的
- (二)、什么是SpringBoot
- 1.基本含义:
- 2.Spring Boot的主要优点
- (三)、微服务
- 1.什么是微服务
- 2.单体应用架构
- 3.微服务架构 (活字印刷)
- 4.如何构建微服务
- (四)、第一个SpringBoot程序
- 1.点击新建文件
- 2.勾选web框架
- 3.进行测试 测试成功
- 5.程序的主入口 (①)
- 6.Pom的配置文件 (②)
- 7.测试Controller(③)
- 8.测试打包
- (五)、SpringBoot 彩蛋 (banner)
- 1.在resource目录下创建一个banner.txt
- 2.重启服务
- (六)⭐YAML⭐
- 1.properties与yaml
- (1).介绍yaml配置文件
- (2).标记语言:
- 2.yaml常用的基本形式
- 3.yaml的作用
- (1).利用注解进行赋值(注解赋值)
- (2).利用yaml进行配置和读取配置属性(@ConfigurationProperties)
- (3).使用properties进行配置和读取配置属性(SPEL)
- (4).yaml的SPEL占位符
- 4.yaml与properties的区别
- 5.松散绑定 (松散语法)
- 6.JSR303校验
- (1).JSR303的总结
- (2).JSR303数据核验的测试
- (七)、SpringBoot自动装配原理
- 1.pom.xml
- 2.主程序
- 3.@SpringBootApplication
- (1).@ComponentScan
- (2).@SpringBootConfiguration
- 4.@EnableAutoConfiguration :
- (1).@AutoConfigurationPackage
- (2).@Import({AutoConfigurationImportSelector.class})
- 5.自动配置生效
- 6.列子
- 7.结论
- (八)、多环境配置即配置文件位置
- 1.application配置的位置
- 2.propertiesd的多环境的切换
- 3.yaml的多文档块
- (九)、自动装配的在理解
- 1.基本点击步骤
- 2.分析自动配置原理
- 3.精髓
- 4.了解:@Conditional
- (十)、SpringBoot web开发
- 1.静态资源导入研究
- (1).创建springWeb项目
- (2).测试环境
- (3).第一种方法:addResourceHandlers 添加资源处理
- (4).第二种方法: 添加静态资源
- 2.首页定制⭐
- (1).放在 static 或 public 或 resource (不能被controller访问)
- (2).放在template目录下 (可以被controller访问)
- 3.图标定制
- (十一)、Thymeleaf模板引擎
- 1.模板引擎
- 2.引入Thymeleaf
- 3.分析Thymeleaf
- 4.Thymeleaf语法(自动装配 .html)
- (1).五种占位符号(表达式)
- (2).测试占位符
- (3).转义与遍历
- (十二)、SpringMVC自动配置原理
- 1.自动配置原理
- 2.转换器和格式化器
- 3.⭐修改SpringBoot的默认配置⭐
(一)、前面回顾
1.什么是Spring
BootStrap官网
http://www.bootstrapmb.com/
https://fanlychie.github.io/post/thymeleaf.html
全局查找:ctrl+f 在本类中进行查找某个方法/属性
shift+shift 在整个idea中搜索某个类
Spring 是一个开源框架,2003年兴起的一个轻量级的java开发框架。
Spring是为了解决企业级应用开发的复杂性创建的 简化开发
2.Spring 是如何简化Java开发的
为了降低Java开发的复杂性,Spring 有如下四种关键策略
- 基于POJO的轻量级和最小性侵入性编程
- 通过IOC,依赖注入和面向接口实现松耦合
- 基于切面 (AOP) 和惯例进行声明式编程
- 通过切面和模板减少样式代码
(二)、什么是SpringBoot
1.基本含义:
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
2.Spring Boot的主要优点
- ⭐为所有Spring 开发者更快的入门
- ⭐开箱即用,提供各种默认配置来简化项目配置
- ⭐ 内嵌式容器简化Web项目
- ⭐没有冗余代码生成和XML配置的要求
(三)、微服务
1.什么是微服务
微服务是一种架构风格,他要求我们在开发一个应用的时候,这个应用必须构建一些列小服务的组合,可以通过http的方式进行互通,要说微服务架构,先得说说过去我们的单体应用架构。
2.单体应用架构
所谓单体应用架构是指: 我们将一个应用的中的所有应用服务都封装在一个应用中。
无论是ERP、CRM或则是其他什么系统,都把数据库访问,web访问,等等各个功能都封装在一个war包内
-⭐ 这样做的好处,易于开发和测试;也十分方便部署;
当需要拓展时,只需要将war复制多份,然后放到服务器上,再做个负载均衡就可以了。
-⭐ 单体用用架构的缺点是: 哪怕我要修改一个非常小的地方,我都需要停掉整个服务,重新打包,部署到整个应用的war包
,特别是对于一个大型应用,我们不可能把所有内容都放在一个应用里面,我们如何维护,如何分工都是问题。
3.微服务架构 (活字印刷)
all in one 的架构方式,我们把所有的功能单元放在一个应用里面。然后我们把整个应用部署到服务器上。如果负载能力不行,我们将整个应用进行水平复制,进行扩展,然后再负载均衡。
所谓微服务架构,就是打破之前 all in one 的架构方式,把每个功能元素独立出来。把每个功能元素独立出来。独立出来的功能元素的动态组合,需要的功能才去拿来组合,需要多一些时可以整合多个功能元素,所以微服务架构是对功能元素进行复制,而没有对整个应用进行复制。
这样做的好处:
- ⭐节省了调用资源
2 . ⭐ 每个功能元素都是一个可替换的、可独立升级的软件代码
程序核心:高内聚(在划分模块时,要把功能关系紧密的放到一个模块中)
低耦合(模块之间的联系越少越好,接口越简单越好)
论文地址:https://martinfowler.com/articles/microservices.html#CharacteristicsOfAMicroserviceArchitecture
4.如何构建微服务
一个大型系统的微服务架构,就像一个复杂交织的神经网络,每一个神经元就是一个功能元素,它们各自完成自己的功能,然后通过http相互请求调用。比如一个电商系统,查缓存、连接数据库、浏览页面、结账、支付宝等服务都是一个独立的功能服务,都被微化了作为一个微服务共同构建了一个庞大的系统。
如果修改其中的一个功能,只需要更新升级其中一个功能服务单元即可。
但是这种庞大的架构给部署和运维带来了很大的难度。于是,Spring为我们带来了构建大型分布式微服务的全套产品。
- 构建一个个功能独立的微服务应用单元,可以使用springboot,可以帮我们快速构建一个应用
- 大型分布式网络服务的调用,这部分springcloud来完成,实现分布式
- 在分布式中间,进行流式数据计算,批处理,我们有spring cloud data flow
- spring为我们想清楚了整个开始构建应用到大型分布式应用全流程方案
(四)、第一个SpringBoot程序
https://springref.com/
- 内嵌了Tomcat,我们不需要配置Tomcat
- 业务层等 我们需要放在与主入口类的同级目录下
1.点击新建文件
2.勾选web框架
我们这里的版本要用: 2.7.7 jdk用1.8 java版本用8
3.进行测试 测试成功
测试控制台
测试Tomcat
5.程序的主入口 (①)
这里是程序的主入口,不能删除
package com.example.springboot01hello;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//本身就是一个SPring程序// 程序的主入口
@SpringBootApplication
public class SpringBoot01HelloApplication {public static void main(String[] args) {SpringApplication.run(SpringBoot01HelloApplication.class, args);System.out.println("你好 吉士先生");}}
6.Pom的配置文件 (②)
- 继承了一个父项目
- 显示jdk版本信息
- web 依赖、单元测试
- 打包插件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<!-- 他有一个父项目 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.7</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>SpringBoot-01-hello</artifactId><version>0.0.1-SNAPSHOT</version><name>SpringBoot-01-hello</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies>
<!-- web 依赖: tomcat dispatcherServlet xml... --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<!-- 单元测试 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
<!-- 打包插件--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
7.测试Controller(③)
必须在程序入口的同级目录下
package com.example.springboot01hello.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HellController {// 实现了自动装配@RequestMapping("/hello")public String hello(){// 调用业务,接受前端的参数return "Hello world";}
}
8.测试打包
(五)、SpringBoot 彩蛋 (banner)
https://www.bootschool.net/ascii-art
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 吉士先生 永不宕机 永无BUG //
1.在resource目录下创建一个banner.txt
2.重启服务
application.xml
在目录上生成日志文件
logging:file:name: log
(六)⭐YAML⭐
1.properties与yaml
SpringBoot使用一个全局的配置文件,配置文件名称是归档的
- application.properties
语法结构: key=value - application.yaml
语法结构: key:空格
value
(1).介绍yaml配置文件
YAML是"YAML Ain't a Markup Language"(YAML不是一种标记语言)的递归缩写
。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)
,但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。
(2).标记语言:
⭐YAML A Markp Language : 是一种标记语言。
⭐YAML isnot Markp Language: 不是一个标记语言。
以前的配置文件。大多数都是使用xml来配置;比如一个简单的端口配置,我们来对比以下yaml和xml的区别。
yaml配置:
# springBoot 的配置文件# 更改Tomcat的端口号
server:port: 8081
# springBoot 的配置文件# 更改Tomcat的端口号
<server>
<port>8081<port>
<server>
2.yaml常用的基本形式
# springBoot 的配置文件 对空格的要求十分高。# 更改Tomcat的端口号
server:port: 8081
# 普通的 Key -valuename: Jsxs
# 对象
student:name: jsxsage: 3
# 对象行内写法
student1: {name: jsxs,age: 2}
#数组
pets:- cate- dog- pig
#数组行内写法
pets1: [cat,dog,pig]
3.yaml的作用
(1).利用注解进行赋值(注解赋值)
在这里我们设置组件(@Compont)和Value(@Value)以及自动装配的(@Resource),可以帮助我们不用配置xml文件,从而实现联结
实体类 dog
package com.example.springboot01hello.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component //设置bean组件的操作
public class Dog {@Value("旺财") // 给属性进行命名的操作 valueprivate String name;@Value("2")private Integer age;public Dog() {}public Dog(String name, Integer age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + age +'}';}
}
实体类人
package com.example.springboot01hello.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.List;
import java.util.Map;@Component
public class people {private String name;private Integer age;private Boolean happy;private Date birth;private Map<String,Object> maps;private List<Object> lists;private Dog dog;public people(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {this.name = name;this.age = age;this.happy = happy;this.birth = birth;this.maps = maps;this.lists = lists;this.dog = dog;}public people() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getHappy() {return happy;}public void setHappy(Boolean happy) {this.happy = happy;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}@Overridepublic String toString() {return "people{" +"name='" + name + '\'' +", age=" + age +", happy=" + happy +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}
}
测试类的实现
package com.example.springboot01hello;import com.example.springboot01hello.pojo.Dog;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;@SpringBootTest
class SpringBoot01HelloApplicationTests {@Resource //进行自动装配的操作,也就是我们前面的private Dog dog;@Testvoid contextLoads() {System.out.println(dog);}}
(2).利用yaml进行配置和读取配置属性(@ConfigurationProperties)
Data日期的格式一定要是: xxxx/xx/xx
添加如下依赖: 我们的就不会爆红了
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><version>2.7.7</version></dependency>
赋值实体类中的 people类
@ConfigurationProperties作用:将配置文件中配置的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定参数: prefix = "person"将配置文件中的person下面的所有书信一一对应只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能这里面的命名不能使用驼峰,全部小写
package com.example.springboot01hello.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.List;
import java.util.Map;@Component
/*@ConfigurationProperties作用:
* 将配置文件中配置的每一个属性的值,映射到这个组件中;
* 告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定
* 参数: prefix = "person"将配置文件中的person下面的所有书信一一对应
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能*/
@ConfigurationProperties(prefix = "person") //这里面的命名不能使用驼峰,全部小写
public class people {private String name;private Integer age;private Boolean happy;private Date birth; //这里的日期格式,一定要是xxxx/xx/xx否则报错private Map<String,Object> maps;private List<Object> lists;private Dog dog;public people(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {this.name = name;this.age = age;this.happy = happy;this.birth = birth;this.maps = maps;this.lists = lists;this.dog = dog;}public people() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getHappy() {return happy;}public void setHappy(Boolean happy) {this.happy = happy;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}@Overridepublic String toString() {return "people{" +"name='" + name + '\'' +", age=" + age +", happy=" + happy +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}
}
配置yaml语句: 包含对象 数组 Map集合 List数组
# 外对象
person:
# 基本属性name: jsxsage: 18happy: Nobirth: 2001/12/01
#键值对maps: {k1: v1,k2: v2}
#数组lists:- code- music- girls
# 内嵌对象dog:name: 旺财age: 15
测试
package com.example.springboot01hello;import com.example.springboot01hello.pojo.Dog;
import com.example.springboot01hello.pojo.people;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;@SpringBootTest
class SpringBoot01HelloApplicationTests {@Resource //进行自动装配的操作,也就是我们前面的private Dog dog;
@Resource
private people people;@Testvoid contextLoads() {System.out.println(dog);System.out.println(people);}
}
(3).使用properties进行配置和读取配置属性(SPEL)
package com.example.springboot01hello.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.List;
import java.util.Map;@Component
//javaConfig 绑定我么配置文件的值,可以采用这些方式
// 加载指定的配置文件
@PropertySource(value = "classpath:jsxs.properties")
public class people {// SPEL表达式读取配置文件的值@Value("${name}")private String name;@Value("${age}")private Integer age;@Value("${happy}")private Boolean happy;@Value("${birth}")private Date birth; //这里的日期格式,一定要是xxxx/xx/xx否则报错private Map<String,Object> maps;private List<Object> lists;private Dog dog;public people(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {this.name = name;this.age = age;this.happy = happy;this.birth = birth;this.maps = maps;this.lists = lists;this.dog = dog;}public people() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getHappy() {return happy;}public void setHappy(Boolean happy) {this.happy = happy;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}@Overridepublic String toString() {return "people{" +"name='" + name + '\'' +", age=" + age +", happy=" + happy +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}
}
利用properties进行配置
通过EL表达式进行获取数据。${}
(4).yaml的SPEL占位符
${}
# 外对象
person:
# 基本属性name: jsxs${random.uuid}age: ${random.int}happy: falsebirth: 2001/12/01hello: sdsdsd
#键值对maps: {k1: v1,k2: v2}
#数组lists:- code- music- girls
# 内嵌对象dog:# 假如说person这个yaml类中不存在hello,那么就会输出hello00_旺财# 假如说存在: 就会输出存在的hello的值name: ${person.hello:hello00}_旺财age: 15
4.yaml与properties的区别
⭐@ConfigurationProperties只需要写一次,value需要每个字段都要加上
⭐松散绑定: 意思就是我的yaml中写的last-name,这个和lastName是一样的,-后面跟着的字母默认是大写的,这就是松散绑定。
⭐JR303数据校验,这个就是我们可以在字段是增加一层过滤器验证,可以保证数据的合法性
。
⭐复杂类型封装,yml中可以封装对象,使用@Value就不支持。
结论
配置yaml和配置properties都可以获取到值 , 但是强烈推荐 yaml
;
如果我们在某个业务中,只需要获取配置文件中的某个值,可以使用一下 @value;
如果说,我们专门编写了一个JavaBean来和配置文件进行一一映射,就直接@configurationProperties,不要犹豫!
5.松散绑定 (松散语法)
就是我们yaml中的last-name等同于实体类中驼峰命名的lastName
实体类的数据
package com.example.springboot01hello.pojo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.List;
import java.util.Map;@Component
/*@ConfigurationProperties作用:
* 将配置文件中配置的每一个属性的值,映射到这个组件中;
* 告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定
* 参数: prefix = "person"将配置文件中的person下面的所有书信一一对应
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能*/
@ConfigurationProperties(prefix = "person") //这里面的命名不能使用驼峰,全部小写@PropertySource(value = "classpath:jsxs.properties")
public class people {private String lastName;private Integer age;private Boolean happy;private Date birth; //这里的日期格式,一定要是xxxx/xx/xx否则报错private Map<String,Object> maps;private List<Object> lists;private Dog dog;public people(String lastName, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {this.lastName = lastName;this.age = age;this.happy = happy;this.birth = birth;this.maps = maps;this.lists = lists;this.dog = dog;}public people() {}public String getlastName() {return lastName;}public void setlastName(String lastName) {this.lastName = lastName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getHappy() {return happy;}public void setHappy(Boolean happy) {this.happy = happy;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}@Overridepublic String toString() {return "people{" +"lastName='" + lastName + '\'' +", age=" + age +", happy=" + happy +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}
}
yaml的配置文件
# 外对象
person:
# 基本属性last-name: jsxs${random.uuid}age: ${random.int}happy: falsebirth: 2001/12/01hello: sdsdsd
#键值对maps: {k1: v1,k2: v2}
#数组lists:- code- music- girls
# 内嵌对象dog:# 假如说person这个yaml类中不存在hello,那么就会输出hello00_旺财# 假如说存在: 就会输出存在的hello的值name: ${person.hello:hello00}_旺财age: 15
6.JSR303校验
实质上就是: 利用注解对数据类型进行初步校验。
需要导入依赖以及添加注解 @Validated //数据校验
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId><version>2.7.7</version>
</dependency>
(1).JSR303的总结
message这个属性就是如果出现错误,我们在控制台打印什么消息
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false 长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则.......等等
除此以外,我们还可以自定义一些数据校验规则
(2).JSR303数据核验的测试
实体类 人
- 添加注解 @Validated //数据校验
- 进行测试邮箱 @Email(message = “邮箱格式错误!”)
package com.example.springboot01hello.pojo;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;@Component
/*@ConfigurationProperties作用:
* 将配置文件中配置的每一个属性的值,映射到这个组件中;
* 告诉SpringBoot将本类中的所有属性和配置文件相关的配置进行绑定
* 参数: prefix = "person"将配置文件中的person下面的所有书信一一对应
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能*/
@ConfigurationProperties(prefix = "person") //这里面的命名不能使用驼峰,全部小写@PropertySource(value = "classpath:jsxs.properties")@Validated //数据校验
public class people {@Email(message = "邮箱格式错误!")private String name;private Integer age;private Boolean happy;private Date birth; //这里的日期格式,一定要是xxxx/xx/xx否则报错private Map<String,Object> maps;private List<Object> lists;private Dog dog;public people(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {this.name = name;this.age = age;this.happy = happy;this.birth = birth;this.maps = maps;this.lists = lists;this.dog = dog;}public people() {}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Boolean getHappy() {return happy;}public void setHappy(Boolean happy) {this.happy = happy;}public Date getBirth() {return birth;}public void setBirth(Date birth) {this.birth = birth;}public Map<String, Object> getMaps() {return maps;}public void setMaps(Map<String, Object> maps) {this.maps = maps;}public List<Object> getLists() {return lists;}public void setLists(List<Object> lists) {this.lists = lists;}public Dog getDog() {return dog;}public void setDog(Dog dog) {this.dog = dog;}@Overridepublic String toString() {return "people{" +"name='" + name + '\'' +", age=" + age +", happy=" + happy +", birth=" + birth +", maps=" + maps +", lists=" + lists +", dog=" + dog +'}';}
}
(七)、SpringBoot自动装配原理
springBoot官方文档
1.pom.xml
- ⭐spring-boot-dependencies: 核心依赖在父工程中!
- ⭐我们在写或则引入一些SpringBoot依赖的时候,不需要指定版本,就因为有这些仓库
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.7</version><relativePath/> <!-- lookup parent from repository --></parent>
<!-- web 依赖: tomcat dispatcherServlet xml... --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
- ⭐启动器: 说白了就是SpringBoot的启动场景
- ⭐比如: spring-boot-starter-web,他就会帮助我们自动导入web环境所有的依赖
- ⭐springBoot会将所有的功能场景,都变成一个个启动器
- ⭐我们要使用什么功能,就只需要找到对应的启动器就可以了
2.主程序
//标注这个类是一个springboot的应用
@SpringBootApplication
public class SpringbootStudyApplication {public static void main(String[] args) {//将springboot应用启动SpringApplication.run(SpringbootStudyApplication.class, args);}
}
在这个里面最重要的就是@SpringBootApplication这个注解了让我们点进去看看,发现他是一个派生注
而这个注解也是一个派生注解,其中的关键功能由@Import提供,其导入的AutoConfigurationImportSelector的selectImports()方法通过SpringFactoriesLoader.loadFactoryNames()扫描所有具有META-INF/spring.factories的jar包。spring-boot-autoconfigure-x.x.x.x.jar里就有一个这样的spring.factories文件。
//springboot的配置
@SpringBootConfiguration//spring配置类@Configuration //说明这也是一个spring的组件@Component //自动配置
@EnableAutoConfiguration//自动配置包@AutoConfigurationPackage //自动配置 @Import(AutoConfigurationPackages.Registrar.class)//自动配置导入选择@Import(AutoConfigurationImportSelector.class)//获取所有的配置
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
获取候选的配置:
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;
}
但是一个简单的启动类并不简单!我们来分析一下这些注解都干了什么
3.@SpringBootApplication
作用:标注在某个类上说明这个类是SpringBoot的主配置类 , SpringBoot就应该运行这个类的main方法来启动SpringBoot应用
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}
), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {// ......
}
(1).@ComponentScan
这个注解在Spring中很重要 ,它对应XML配置中的元素。
作用:自动扫描并加载符合条件的组件或者bean , 将这个bean定义加载到IOC容器中
(2).@SpringBootConfiguration
作用:SpringBoot的配置类 ,标注在某个类上 , 表示这是一个SpringBoot的配置类;
我们继续进去这个注解查看
// 点进去得到下面的 @Component
@Configuration
public @interface SpringBootConfiguration {}@Component
public @interface Configuration {}
这里的 @Configuration,说明这是一个配置类 ,配置类就是对应Spring的xml 配置文件;
里面的 @Component 这就说明,启动类本身也是Spring中的一个组件而已,负责启动应用!
我们回到 SpringBootApplication 注解中继续看,而在这些个注解中最重要的就是@EnableAutoConfiguration,我们继续点进去看,在这些个注解中最重要的就是@EnableAutoConfiguration,我们继续点进去看
4.@EnableAutoConfiguration :
开启自动配置功能
以前我们需要自己配置的东西,而现在SpringBoot可以自动帮我们配置 ;@EnableAutoConfiguration告诉SpringBoot开启自动配置功能,这样自动配置才能生效;
(1).@AutoConfigurationPackage
翻译:自动配置包
@Import({Registrar.class})
//利用Registrar导入一系列组件
//将指定的一个包下的所有组件导入进来?是主程序所在的包下
public @interface AutoConfigurationPackage {}
@import :Spring底层注解@import , 给容器中导入一个组件
Registrar.class 作用:将主启动类的所在包及包下面所有子包里面的所有组件扫描到Spring容器 ;
这个分析完了,退到上一步,继续看
(2).@Import({AutoConfigurationImportSelector.class})
给容器导入组件 ;
而这个注解也是一个派生注解,其中的关键功能由**@Import**提供,其导入的AutoConfigurationImportSelector的selectImports()方法通过SpringFactoriesLoader.loadFactoryNames()扫描所有具有META-INF/spring.factories的jar包。spring-boot-autoconfigure-x.x.x.x.jar里就有一个这样的spring.factories文件。
AutoConfigurationImportSelector :自动配置导入选择器,那么它会导入哪些组件的选择器呢?我们点击去这个类看源码:
1、这个类中有一个这样的方法
// 获得候选的配置
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {//这里的getSpringFactoriesLoaderFactoryClass()方法//返回的就是我们最开始看的启动自动导入配置文件的注解类;EnableAutoConfigurationList<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}
2、这个方法又调用了SpringFactoriesLoader 类的静态方法!我们进入SpringFactoriesLoader类loadFactoryNames() 方法
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {String factoryClassName = factoryClass.getName();//这里它又调用了 loadSpringFactories 方法return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
3、我们继续点击查看 loadSpringFactories 方法
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {//获得classLoader , 我们返回可以看到这里得到的就是EnableAutoConfiguration标注的类本身MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);if (result != null) {return result;} else {try {//去获取一个资源 "META-INF/spring.factories"Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");LinkedMultiValueMap result = new LinkedMultiValueMap();//将读取到的资源遍历,封装成为一个Propertieswhile(urls.hasMoreElements()) {URL url = (URL)urls.nextElement();UrlResource resource = new UrlResource(url);Properties properties = PropertiesLoaderUtils.loadProperties(resource);Iterator var6 = properties.entrySet().iterator();while(var6.hasNext()) {Entry<?, ?> entry = (Entry)var6.next();String factoryClassName = ((String)entry.getKey()).trim();String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());int var10 = var9.length;for(int var11 = 0; var11 < var10; ++var11) {String factoryName = var9[var11];result.add(factoryClassName, factoryName.trim());}}}cache.put(classLoader, result);return result;} catch (IOException var13) {throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);}}
}
4.发现一个多次出现的文件:spring.factories,全局搜索它
spring.factories
文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
我们根据源头打开spring.factories , 看到了很多自动配置的文件;这就是自动配置根源所在!
这个spring.factories文件也是一组一组的key=value的形式,其中一个key是EnableAutoConfiguration类的全类名,而它的value是一个xxxxAutoConfiguration的类名的列表,这些类名以逗号分隔,如下图所示:
这个@EnableAutoConfiguration注解通过@SpringBootApplication被间接的标记在了Spring Boot的启动类上。在SpringApplication.run(…)的内部就会执行selectImports()方法,找到所有JavaConfig自动配置类的全限定名对应的class,然后将所有自动配置类加载到Spring容器中。
WebMvcAutoConfiguration
可以看到这些一个个的都是JavaConfig配置类,而且都注入了一些Bean,可以找一些自己认识的类,看着熟悉一下!
所以,自动配置真正实现是从classpath中搜寻所有的META-INF/spring.factories配置文件 ,并将其中对应的 org.springframework.boot.autoconfigure. 包下的配置项,通过反射实例化为对应标注了 @Configuration的JavaConfig形式的IOC容器配置类 , 然后将这些都汇总成为一个实例并加载到IOC容器中。
5.自动配置生效
每一个XxxxAutoConfiguration自动配置类都是在某些条件之下才会生效的,这些条件的限制在Spring Boot中以注解的形式体现,常见的条件注解有如下几项:
@ConditionalOnBean:当容器里有指定的bean的条件下。@ConditionalOnMissingBean:当容器里不存在指定bean的条件下。@ConditionalOnClass:当类路径下有指定类的条件下。@ConditionalOnMissingClass:当类路径下不存在指定类的条件下。@ConditionalOnProperty:指定的属性是否有指定的值,比如@ConditionalOnProperties(prefix=”xxx.xxx”, value=”enable”, matchIfMissing=true),代表当xxx.xxx为enable时条件的布尔值为true,如果没有设置的情况下也为true。
6.列子
以ServletWebServerFactoryAutoConfiguration配置类为例,解释一下全局配置文件中的属性如何生效,比如:server.port=8081,是如何生效的(当然不配置也会有默认值,这个默认值来自于org.apache.catalina.startup.Tomcat)。
在ServletWebServerFactoryAutoConfiguration类上,有一个@EnableConfigurationProperties注解:开启配置属性,而它后面的参数是一个ServerProperties类,这就是约定大于配置的最终落地点。
7.结论
1.SpringBoot所有自动配置都是在启动的时候扫描并加载
: spring.factories
所有的自动装配都在这里面,但是不一定生效,要判断条件是否成立,只要导入对应的start,就有对应的启动器了,有了启动器,我们自动装配就会生效,然后就配置成功。
2.springBoot在启动的时候,从类路径下/META-INF/spring.factories
获取指定的值。
3.将这些自动配置的类导入容器,自动配置就会生效,帮我们进行自动装配
4.整合javaSE,解决方案和自动配置的东西都在spring-boot-a下
5.以前我们需要自动配置的东西,现在SpringBoot帮我们做了
6.他会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器
7.容器中也会存在非常多的xxxAppliconfigation的文件,这些文件就会导入对应的组件;并且自动配置
8.有了自动配置类,我们就免去了手动装配文件
。
SpringApplication.run分析
分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;
SpringApplication
这个类主要做了以下四件事情:
1、推断应用的类型是普通的项目还是Web项目
2、查找并加载所有可用初始化器 , 设置到initializers属性中
3、找出所有的应用程序监听器,设置到listeners属性中
4、推断并设置main方法的定义类,找到运行的主类
查看构造器:
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {// ......this.webApplicationType = WebApplicationType.deduceFromClasspath();this.setInitializers(this.getSpringFactoriesInstances();this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));this.mainApplicationClass = this.deduceMainApplicationClass();
}
关于springboot,谈谈你的理解:
springboot的自动装配
run():
①判断当前项目是普通项目还是web项目
②推断并设置main方法的定义类,找到运行的主类
③run方法里面有一些监听器,这些监听器是全局存在的,它的作用是获取上下文处理一些bean,所有的bean无论是加载还是生产初始化多存在。
(八)、多环境配置即配置文件位置
1.application配置的位置
优先级1:项目路径下的config文件夹配置文件
优先级2:项目路径下配置文件
优先级3:资源路径下的config文件夹配置文件
优先级4:资源路径下配置文件
优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件;互补配置;
我们在最低级的配置文件中设置一个项目访问路径的配置来测试互补问题;
2.propertiesd的多环境的切换
我们在文档中设置的有三个环境,第一个是: 默认环境(application.properties)。第二个是: 测试环境(application-test.properties)。 第三个是: 开发环境(application-dev.properties)
假如说我们要进行切换环境的话,我们可以设置如下的代码
spring.profiles.active='走的环境'
# 默认环境下是8080
server.port=8080
#springboot的多环境配置,可以选择激活哪一个配置文件#spring.profiles.active=dev 这样是走开发环境spring.profiles.active=test
3.yaml的多文档块
yaml文档之间的分割时 - - -
三个连续的杠。相当于properties的文档,但是不需要创建文件,我们只需要划三个杠。
指定开启dev这个端口号
spring:profiles:active: dev
# 端口号1
server:port: 8081
---
#端口号2
server:port: 8082
spring:profiles:active: dev---
#端口号3
server:port: 8083
spring:profiles: test
(九)、自动装配的在理解
1.基本点击步骤
2.分析自动配置原理
我们以HttpEncodingAutoConfiguration(Http编码自动配置)
为例解释自动配置原理;
@Configuration //表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件;//启动指定类的ConfigurationProperties功能;//进入这个HttpProperties查看,将配置文件中对应的值和HttpProperties绑定起来;//并把HttpProperties加入到ioc容器中
@EnableConfigurationProperties({HttpProperties.class}) //Spring底层@Conditional注解//根据不同的条件判断,如果满足指定的条件,整个配置类里面的配置就会生效;//这里的意思就是判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication(type = Type.SERVLET)//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnClass({CharacterEncodingFilter.class})//判断配置文件中是否存在某个配置:spring.http.encoding.enabled;//如果不存在,判断也是成立的//即使我们配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的;
@ConditionalOnProperty(prefix = "spring.http.encoding",value = {"enabled"},matchIfMissing = true
)public class HttpEncodingAutoConfiguration {//他已经和SpringBoot的配置文件映射了private final Encoding properties;//只有一个有参构造器的情况下,参数的值就会从容器中拿public HttpEncodingAutoConfiguration(HttpProperties properties) {this.properties = properties.getEncoding();}//给容器中添加一个组件,这个组件的某些值需要从properties中获取@Bean@ConditionalOnMissingBean //判断容器没有这个组件?public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));return filter;}//。。。。。。。
}
一句话总结 :根据当前不同的条件判断,决定这个配置类是否生效!
- 一但这个配置类生效;这个配置类就会给容器中添加各种组件;
- 这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的; 这样就可以形成我们的配置文件可以动态的修改springboot的内容。
- 所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;
- 配置文件能配置什么就可以参照某个功能对应的这个属性类
通俗理解:把我们原先需要在bean中手打的属性(property)封装成了一个类,然后通过yaml文件进行自动注入,而我们也可以在application.yaml文件中对这些property进行赋值。
//从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(prefix = "spring.http")
public class HttpProperties {// .....
}
3.精髓
1.SpringBoot启动时会加载大量的自动配置类
2.我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中
3.我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在其中,我们就不需要再去手动配置了,如果不存在我们再手动配置)
4.给容器中自动配置类添加组件的时候,会从properties类中获取某些属性,我们只需要在配置文件中指定这些属性即可;
XXXXAutoConfiguration:自动配置类:给容器添加组件,这些组件要赋值就需要绑定一个XXXXProperties类
XXXXProperties:里面封装配置文件中相关属性;
怎么去修改这些属性呢:说白了就是SpringBoot配置,---->.yaml、.properties这些文件
4.了解:@Conditional
了解完自动装配的原理后,我们来关注一个细节问题,*自动配置类必须在一定的条件下才能生效;
@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;
那么多的自动配置类,必须在一定的条件下才能生效;也就是说,我们加载了这么多的配置类,但不是所有的都生效了。
我们怎么知道哪些自动配置类生效?
我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;
#开启springboot的调试类
debug=true
Positive matches:(自动配置类启用的:正匹配)
Negative matches:(没有启动,没有匹配成功的自动配置类:负匹配)
Unconditional classes: (没有条件的类)
【演示:查看输出的日志】
掌握吸收理解原理,即可以不变应万变!
(十)、SpringBoot web开发
在之前我们的项目都是以jar包结尾的,没有放webapp的地方。
springboot最大的特点:自动装配
springboot到底帮我们配置了什么,我们能不能修改?能修改哪些东西?能不能扩展?
- xxxAutoConfiguration… 向容器中自动配置组件
- xxxProperties: 自动配置类:装配配置文件中自定义的一些内容
要解决的问题:
- 导入静态资源
- 首页
- jsp,模板引擎 Thymeleaf
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 国际化!
1.静态资源导入研究
(1).创建springWeb项目
(2).测试环境
设置controller层,并创建test类,里面使用JSON的注解 @RestController.查看数据示范展现出来
package com.jsxs.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Test {@RequestMapping("/hello")public String test(){return "hello world!";}
}
测试成功!!!!
如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面的,对吧!但是我们现在的pom呢,打包方式是为jar的方式,那么这种方式SpringBoot能不能来给我们写页面呢?当然是可以的,但是SpringBoot对于静态资源放置的位置,是有规定的!
我们先来聊聊这个静态资源映射规则:
pringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;
我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;
(3).第一种方法:addResourceHandlers 添加资源处理
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {if (!this.resourceProperties.isAddMappings()) {// 已禁用默认资源处理logger.debug("Default resource handling disabled");return;}// 缓存控制Duration cachePeriod = this.resourceProperties.getCache().getPeriod();CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();// webjars 配置if (!registry.hasMappingForPattern("/webjars/**")) {customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));}// 静态资源配置String staticPathPattern = this.mvcProperties.getStaticPathPattern();if (!registry.hasMappingForPattern(staticPathPattern)) {customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));}
}
读一下源代码:比如所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;
什么是webjars 呢?
Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。
使用SpringBoot需要使用Webjars,我们可以去搜索一下:
网站:https://www.webjars.org
要使用jquery我们要导入对应的 jquery版本
<dependency><groupId>org.webjars.npm</groupId><artifactId>jquery</artifactId><version>3.4.1</version>
</dependency>
访问:只要是静态资源,SpringBoot就会去对应的路径寻找资源,我们这里访问:http://localhost:8080/webjars/jquery/3.4.1/dist/jquery.js
(4).第二种方法: 添加静态资源
那我们项目中要是使用自己的静态资源该怎么导入呢?我们看下一行代码;
我们去找staticPathPattern发现第二种映射规则 :/** , 访问当前的项目任意资源,它会去找 resourceProperties 这个类,我们可以点进去看一下分析
// 进入方法
public String[] getStaticLocations() {return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/"
};
三种 优先级
ResourceProperties 可以设置和我们静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。
我们访问的连接是: http://localhost:8080/**
所以得出结论,以下四个目录存放的静态资源可以被我们识别:
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
我们可以在resources根目录下新建对应的文件夹,都可以存放我们的静态文件;
比如我们访问 http://localhost:8080/2.js , 他就会去这些文件夹中寻找对应的静态资源文件;
自定义静态资源路径
我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;
spring.resources.static-locations=classpath:/coding/,classpath:/kuang/
一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!
2.首页定制⭐
(1).放在 static 或 public 或 resource (不能被controller访问)
静态资源文件夹说完后,我们继续向下看源码!可以看到一个欢迎页的映射,就是我们的首页!
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,FormattingConversionService mvcConversionService,ResourceUrlProvider mvcResourceUrlProvider) {WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // getWelcomePage 获得欢迎页this.mvcProperties.getStaticPathPattern());welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));return welcomePageHandlerMapping;
}
点进去继续看
private Optional<Resource> getWelcomePage() {String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());// ::是java8 中新引入的运算符// Class::function的时候function是属于Class的,应该是静态方法。// this::function的funtion是属于这个对象的。// 简而言之,就是一种语法糖而已,是一种简写return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
// 欢迎页就是一个location下的的 index.html 而已
private Resource getIndexHtml(String location) {return this.resourceLoader.getResource(location + "index.html");
}
/ 拦截所有请求 包括静态资源和动态请求 但是不拦截jsp
/*拦截所有请求 包括静态资源和动态请求 也拦截jsp
区别就在于/ 不拦截jsp /*拦截jsp/* 是拦截所有的文件夹,不包含子文件夹
/** 是拦截所有的文件夹及里面的子文件夹相当于/*只有后面一级/** 可以包含多级
欢迎页,静态资源文件夹下的所有 index.html 页面;被 /** 映射。
比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html
新建一个 index.html ,在我们上面的3个目录中任意一个
;然后访问测试 http://localhost:8080/ 看结果!
(2).放在template目录下 (可以被controller访问)
测试能够直接访问能行不?---不行。在template目录下的所有页面,只能通过controller来跳转。
controller层
package com.jsxs.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;//在template目录下的所有页面,只能通过controller来跳转。
@Controller
// 这里我们
public class indexController {@RequestMapping("/index")public String index(Model model){model.addAttribute("msg","Hello JSXS");return "index";}
}
这在里会报404的错误,因为我们还需要一个引擎
报错505错误,是因为我们映射的地址不能和下面的地址一致。
我们导入Thymeleaf的依赖之后:访问成功
全局查找:ctrl+f 在本类中进行查找某个方法/属性
shift+sgift 在整个idea中搜索某个类
3.图标定制
把favicon.ico放在以下目录,会自动转换成网站的图标
"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
优先级 META-INF/resources > resources > static(默认) > public
如果刷新不出来 直接进行浏览器强制刷新 ctrl +f5 !!!!!!!
(十一)、Thymeleaf模板引擎
1.模板引擎
前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。
jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war,像第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢?
SpringBoot推荐你可以来使用模板引擎:
模板引擎,我们其实大家听到很多,其实jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的,什么样一个思想呢我们来看一下这张图:
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
我们呢,就来看一下这个模板引擎,那既然要看这个模板引擎。首先,我们来看SpringBoot里边怎么用。
2.引入Thymeleaf
怎么引入呢,对于springboot来说,什么事情不都是一个start的事情嘛,我们去在项目中引入一下。给大家三个网址:
Thymeleaf 官网:
https://www.thymeleaf.org/
Thymeleaf 在Github 的主页:
https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.7.7/reference/htmlsingle/#using.build-systems.starters
找到对应的pom依赖:可以适当点进源码看下本来的包!
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId><version>2.7.7</version></dependency>
3.分析Thymeleaf
前面呢,我们已经引入了Thymeleaf,那这个要怎么使用呢?
我们首先得按照SpringBoot的自动配置原理看一下我们这个Thymeleaf的自动配置规则,在按照那个规则,我们进行使用。
我们去找一下Thymeleaf的自动配置类:ThymeleafProperties
@ConfigurationProperties(prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {private static final Charset DEFAULT_ENCODING;public static final String DEFAULT_PREFIX = "classpath:/templates/";public static final String DEFAULT_SUFFIX = ".html";private boolean checkTemplate = true;private boolean checkTemplateLocation = true;private String prefix = "classpath:/templates/";private String suffix = ".html";private String mode = "HTML";private Charset encoding;
}
我们可以在其中看到默认的前缀和后缀!
我们只需要把我们的html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了。
使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!
编写controller 放在controller包下
package com.jsxs.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;//在template目录下的所有页面,只能通过controller来跳转。
@Controller
// 这里我们需要模板引擎的支持,thymplao
public class indexController {@RequestMapping("/a")public String index(Model model){model.addAttribute("msg","Hello JSXS");return "index";}
}
编写index.html 放在template目录下
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>首页</title></head>
<body>
12212
</body>
</html>
测试结果
4.Thymeleaf语法(自动装配 .html)
首先我们应该在Html里面导入 thymeleaf的语句
<html lang="en" xmlns:th="http://www.thymeleaf.org">
(1).五种占位符号(表达式)
- ${xxx} 取变量
- *{xxx} 选择的表达式
- #{xxx} 消息(国际化消息)
- @{xxx} URL
- ~{xxx} 插槽组件
(2).测试占位符
设置controller层
package com.jsxs.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;//在template目录下的所有页面,只能通过controller来跳转。
@Controller
// 这里我们需要模板引擎的支持,thymplao
public class indexController {@RequestMapping("/a")public String index(Model model){model.addAttribute("msg","Hello JSXS");return "index";}
}
设置html层 先导入配置语句 然后设置div块。
为了区分,这里和Vue一样。我们要使用 th: 进行区分所有的html语句都可以被 thymeleaf 接管 。通过 th:属性
<!DOCTYPE html>
<!-- 配置thymeleaf语句-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>首页</title></head>
<body>
<!-- 为了区分,这里和Vue一样。我们要使用 th: 进行区分所有的html语句都可以被 thymeleaf 接管 。通过 th:属性
-->
<div th:text="${msg}"></div>
</body>
</html>
OK,入门搞定,我们来认真研习一下Thymeleaf的使用语法!
1、我们可以使用任意的 th:attr 来替换Html中原生属性的值!
2、我们能写哪些表达式呢?
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;1)、获取对象的属性、调用方法2)、使用内置的基本对象:#18#ctx : the context object.#vars: the context variables.#locale : the context locale.#request : (only in Web Contexts) the HttpServletRequest object.#response : (only in Web Contexts) the HttpServletResponse object.#session : (only in Web Contexts) the HttpSession object.#servletContext : (only in Web Contexts) the ServletContext object.3)、内置的一些工具对象:#execInfo : information about the template being processed.#uris : methods for escaping parts of URLs/URIs#conversions : methods for executing the configured conversion service (if any).#dates : methods for java.util.Date objects: formatting, component extraction, etc.#calendars : analogous to #dates , but for java.util.Calendar objects.#numbers : methods for formatting numeric objects.#strings : methods for String objects: contains, startsWith, prepending/appending, etc.#objects : methods for objects in general.#bools : methods for boolean evaluation.#arrays : methods for arrays.#lists : methods for lists.#sets : methods for sets.#maps : methods for maps.#aggregates : methods for creating aggregates on arrays or collections.
==================================================================================Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;Message Expressions: #{...}:获取国际化内容Link URL Expressions: @{...}:定义URL;Fragment Expressions: ~{...}:片段引用表达式Literals(字面量)Text literals: 'one text' , 'Another one!' ,…Number literals: 0 , 34 , 3.0 , 12.3 ,…Boolean literals: true , falseNull literal: nullLiteral tokens: one , sometext , main ,…Text operations:(文本操作)String concatenation: +Literal substitutions: |The name is ${name}|Arithmetic operations:(数学运算)Binary operators: + , - , * , / , %Minus sign (unary operator): -Boolean operations:(布尔运算)Binary operators: and , orBoolean negation (unary operator): ! , notComparisons and equality:(比较运算)Comparators: > , < , >= , <= ( gt , lt , ge , le )Equality operators: == , != ( eq , ne )Conditional operators:条件运算(三元运算符)If-then: (if) ? (then)If-then-else: (if) ? (then) : (else)Default: (value) ?: (defaultvalue)Special tokens:No-Operation: _
(3).转义与遍历
特殊字符转义: 就是指直接原样输出
特殊字符不转义: 就是指不原样输出
遍历的两种写法:
编写controller层的数据,变量和数组
package com.jsxs.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;
import java.util.Arrays;//在template目录下的所有页面,只能通过controller来跳转。
@Controller
// 这里我们需要模板引擎的支持,thymplao
public class indexController {@RequestMapping("/a")public String index(Model model){model.addAttribute("msg","<h1>Hello JSXS</h1>");model.addAttribute("user", Arrays.asList("jsxs","JSXS"));return "index";}
}
index.html 接收数据. 第一种接受遍历${遍历的值},第二种接受遍历[[ ${遍历的值}]]
<!DOCTYPE html>
<!-- 配置thymeleaf语句-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>首页</title></head>
<body>
<!-- 转义字符 : 原样输出-->
<div th:text="${msg}"></div>
<!-- 不转义字符: 不原样输出-->
<div th:utext="${msg}"></div><hr><ul><li th:each="users:${user}" th:text="${users}"></li>
</ul>
<hr><h1 th:each="user1:${user}">[[${user1} ]]</h1>
</body>
</html>
(十二)、SpringMVC自动配置原理
1.自动配置原理
在进行项目编写前,我们还需要知道一个东西,就是SpringBoot对我们的SpringMVC还做了哪些配置,包括如何扩展,如何定制。
只有把这些都搞清楚了,我们在之后使用才会更加得心应手。途径一:源码分析,途径二:官方文档!
官方文档
Spring MVC Auto-configuration
// Spring Boot为Spring MVC提供了自动配置,它可以很好地与大多数应用程序一起工作。
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
// 自动配置在Spring默认设置的基础上添加了以下功能:
The auto-configuration adds the following features on top of Spring’s defaults:
// 包含视图解析器
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
// 支持静态资源文件夹的路径,以及webjars
Support for serving static resources, including support for WebJars
// 自动注册了Converter:
// 转换器,这就是我们网页提交数据到后台自动封装成为对象的东西,比如把"1"字符串自动转换为int类型
// Formatter:【格式化器,比如页面给我们了一个2019-8-10,它会给我们自动格式化为Date对象】
Automatic registration of Converter, GenericConverter, and Formatter beans.
// HttpMessageConverters
// SpringMVC用来转换Http请求和响应的的,比如我们要把一个User对象转换为JSON字符串,可以去看官网文档解释;
Support for HttpMessageConverters (covered later in this document).
// 定义错误代码生成规则的
Automatic registration of MessageCodesResolver (covered later in this document).
// 首页定制
Static index.html support.
// 图标定制
Custom Favicon support (covered later in this document).
// 初始化数据绑定器:帮我们把请求数据绑定到JavaBean中!
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document)./*
如果您希望保留Spring Boot MVC功能,并且希望添加其他MVC配置(拦截器、格式化程序、视图控制器和其他功能),则可以添加自己
的@configuration类,类型为webmvcconfiguer,但不添加@EnableWebMvc。如果希望提供
RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义
实例,则可以声明WebMVCregistrationAdapter实例来提供此类组件。
*/
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration
(interceptors, formatters, view controllers, and other features), you can add your own
@Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide
custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or
ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.// 如果您想完全控制Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc进行注释。
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
我们来仔细对照,看一下它怎么实现的,它告诉我们SpringBoot已经帮我们自动配置好了SpringMVC,然后自动配置了哪些东西呢?
ContentNegotiatingViewResolver 内容协商视图解析器
自动配置了ViewResolver,就是我们之前学习的SpringMVC的视图解析器;
即根据方法的返回值取得视图对象(View),然后由视图对象决定如何渲染(转发,重定向)。
我们去看看这里的源码:我们找到 WebMvcAutoConfiguration , 然后搜索ContentNegotiatingViewResolver。找到如下方法!
@Bean
@ConditionalOnBean(ViewResolver.class)
@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));// ContentNegotiatingViewResolver使用所有其他视图解析器来定位视图,因此它应该具有较高的优先级resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);return resolver;
}
我们可以点进这类看看!找到对应的解析视图的代码;
@Nullable // 注解说明:@Nullable 即参数可为null
public View resolveViewName(String viewName, Locale locale) throws Exception {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());if (requestedMediaTypes != null) {// 获取候选的视图对象List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);// 选择一个最适合的视图对象,然后把这个对象返回View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);if (bestView != null) {return bestView;}}// .....
}
我们继续点进去看,他是怎么获得候选的视图的呢?
getCandidateViews中看到他是把所有的视图解析器拿来,进行while循环,挨个解析!
Iterator var5 = this.viewResolvers.iterator();
所以得出结论:ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的
我们再去研究下他的组合逻辑,看到有个属性viewResolvers,看看它是在哪里进行赋值的!
protected void initServletContext(ServletContext servletContext) {// 这里它是从beanFactory工具中获取容器中的所有视图解析器// ViewRescolver.class 把所有的视图解析器来组合的Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.obtainApplicationContext(), ViewResolver.class).values();ViewResolver viewResolver;if (this.viewResolvers == null) {this.viewResolvers = new ArrayList(matchingBeans.size());}// ...............
}
既然它是在容器中去找视图解析器,我们是否可以猜想,我们就可以去实现一个视图解析器了呢?
实现试图解析接口的类,我们就称它为视图解析器。
视图解析接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//package org.springframework.web.servlet;import java.util.Locale;
import org.springframework.lang.Nullable;public interface ViewResolver {@NullableView resolveViewName(String viewName, Locale locale) throws Exception;
}
我们可以自己给容器中去添加一个视图解析器;这个类就会帮我们自动的将它组合进来;我们去实现一下
1、我们在我们的主程序中去写一个视图解析器来试试;
@Bean //放到bean中
public ViewResolver myViewResolver(){return new MyViewResolver();
}//我们写一个静态内部类,视图解析器就需要实现ViewResolver接口
private static class MyViewResolver implements ViewResolver{@Overridepublic View resolveViewName(String s, Locale locale) throws Exception {return null;}
}
2、怎么看我们自己写的视图解析器有没有起作用呢?
我们给 DispatcherServlet 中的 doDispatch方法 加个断点进行调试一下,因为所有的请求都会走到这个方法中
3、我们启动我们的项目,然后随便访问一个页面(localhost:8080),看一下Debug信息;
找到视图解析器,我们看到我们自己定义的就在这里了;
所以说,我们如果想要使用自己定制化的东西,我们只需要给容器中添加这个组件就好了!剩下的事情SpringBoot就会帮我们做了!
2.转换器和格式化器
找到格式化转换器:
@Bean
@Override
public FormattingConversionService mvcConversionService() {// 拿到配置文件中的格式化规则WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());addFormatters(conversionService);return conversionService;
}
点击去:
public String getDateFormat() {return this.dateFormat;
}
/**
* Date format to use. For instance, `dd/MM/yyyy`. 默认的*/
private String dateFormat;
可以看到在我们的Properties文件中,我们可以进行自动配置它!
如果配置了自己的格式化方式,就会注册到Bean中生效,我们可以在配置文件中配置日期格式化的规则:
3.⭐修改SpringBoot的默认配置⭐
这么多的自动配置,原理都是一样的,通过这个WebMVC的自动配置原理分析,我们要学会一种学习方式,通过源码探究,得出结论;这个结论一定是属于自己的,而且一通百通。
SpringBoot的底层,大量用到了这些设计细节思想,所以,没事需要多阅读源码!得出结论;
SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(如果用户自己配置@bean),如果有就用用户配置的,如果没有就用自动配置的;
如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来!
扩展使用SpringMVC 官方文档如下:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解;我们去自己写一个;我们新建一个包叫config,写一个类MyMvcConfig;
package com.jsxs.config;//全面扩展 springmvcimport org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;// 我们要重新配置MyMvcConfig, 我们要设置Configuration这个注解@Configuration
public class MyMvcConfig implements WebMvcConfigurer {// 这个方法就是我们配置视图解析器@Overridepublic void addViewControllers(ViewControllerRegistry registry) {// 这里的方法就是我们假如走 /jsxs 这个路径,我们就会走index这个页面。registry.addViewController("/jsxs").setViewName("index");}
}
确实也跳转过来了!所以说,我们要扩展SpringMVC,官方就推荐我们这么去使用,既保SpringBoot留所有的自动配置,也能用我们扩展的配置!
我们可以去分析一下原理:
1、WebMvcAutoConfiguration 是 SpringMVC的自动配置类,里面有一个类WebMvcAutoConfigurationAdapter
2、这个类上有一个注解,在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
3、我们点进EnableWebMvcConfiguration这个类看一下,它继承了一个父类:DelegatingWebMvcConfiguration
这个父类中有这样一段代码:
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();// 从容器中获取所有的webmvcConfigurer@Autowired(required = false)public void setConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);}}
}
4、我们可以在这个类中去寻找一个我们刚才设置的viewController当做参考,发现它调用了一个
protected void addViewControllers(ViewControllerRegistry registry) {this.configurers.addViewControllers(registry);
}
5、我们点进去看一下
public void addViewControllers(ViewControllerRegistry registry) {Iterator var2 = this.delegates.iterator();while(var2.hasNext()) {// 将所有的WebMvcConfigurer相关配置来一起调用!包括我们自己配置的和Spring给我们配置的WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next();delegate.addViewControllers(registry);}}
所以得出结论:所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用;
87.【SpringBoot-01】相关推荐
- 【Springboot+mybatis】 解析Excel并批量导入到数据库
[Springboot+mybatis] 解析Excel并批量导入到数据库 置顶 2018年01月16日 20:05:52 冉野丶 阅读数:4060 标签: excel导入数据库 文件上传 excel ...
- 【重难点】【分布式 01】RESTful、RPC 对比、Dubbo、Spring Cloud 对比、Eureka、Zookeeper、Consul、Nacos 对比、分布式锁
[重难点][分布式 01]RESTful.RPC 对比.Dubbo.Spring Cloud 对比.Eureka.Zookeeper.Consul.Nacos 对比.分布式锁 文章目录 [重难点][分 ...
- 【重难点】【RabbitMQ 01】消息队列的作用、主流的消息队列、RabbitMQ 基于什么传输消息、RabbitMQ 模型架构、死信队列和延迟队列
[重难点][RabbitMQ 01]消息队列的作用.主流的消息队列.RabbitMQ 基于什么传输消息.RabbitMQ 模型架构.死信队列和延迟队列 文章目录 [重难点][RabbitMQ 01]消 ...
- 【重难点】【Redis 01】为什么使用 Redis、Redis 的线程模型、Redis 的数据类型及其底层数据结构
[重难点][Redis 01]为什么使用 Redis.Redis 的线程模型.Redis 的数据类型及其底层数据结构 文章目录 [重难点][Redis 01]为什么使用 Redis.Redis 的线程 ...
- 【重难点】【JUC 01】线程安全都体现在哪些方面 、如何维护线程安全、多线程的同步方法、多线程通信方式、AQS
[重难点][JUC 01]线程安全都体现在哪些方面 .如何维护线程安全.多线程的同步方法.多线程通信方式.AQS 文章目录 [重难点][JUC 01]线程安全都体现在哪些方面 .如何维护线程安全.多线 ...
- 【重难点】【JVM 01】OOM 出现的原因、方法区、类加载机制、JVM 中的对象
[重难点][JVM 01]OOM 出现的原因.方法区.类加载机制.JVM 中的对象 文章目录 [重难点][JVM 01]OOM 出现的原因.方法区.类加载机制.JVM 中的对象 一.OOM 出现的原因 ...
- 【初级01】java JVM核心技术(1):字节码、类加载器、GC机制
1.编程语言概述 编程语言有不同的分类方法: 面向过程.面向对象.面向函数 静态类型.动态类型 编译执行.解释执行 有虚拟机.无虚拟机 有GC.无GC Java语言是一种面向对象.静态类型.编译执行, ...
- 【Springboot学习】SpringBoot集成Shiro前后端分离使用redis做缓存【个人博客搭建】
shiro-redis 目录 shiro-redis 下载 shiro-core/jedis 版本对比图 使用前 如何配置? 设置文件 Redis 独立 Redis哨兵 Redis 集群 Spring ...
- 【SpringBoot专题】整合mybatis-plus之封装查询参数简化查询
[SpringBoot专题]整合mybatis-plus之封装查询参数简化查询 通常开发过程中,操作数据库是作为后端开发必要掌握的本领,今天分享的是springboot整合mybatis-plus,官 ...
- 【重难点】【计算机网络 01】OSI 七层模型和 TCP/IP 四层模型、IP 地址分为哪几类、ping 的原理、从浏览器地址栏输入 URL 到显示网页的过程、什么是 socket
[重难点][计算机网络 01]OSI 七层模型和 TCP/IP 四层模型.IP 地址分为哪几类.ping 的原理.从浏览器地址栏输入 URL 到显示网页的过程.什么是 socket 文章目录 [重难点 ...
最新文章
- Timer的缺陷 用ScheduledExecutorService替代
- Matlab 进行离散时间信号序列的生成
- 使用ASP.NET Core 3.x 构建 RESTful API - 3.2 路由
- oracle binary_integer pls_integer,oracle中binaryinteger与plsinteger的区别
- python 文件修改记录_python基础-文件增删改查
- 2021福州地区高考成绩排名查询,2021年福州各高中高考成绩排名及放榜最新消息...
- Fault Tolerance 要求、限制和许可
- DSB2017第一名论文理解: 3D Deep Leaky Noisy-or Network(二)
- 智能提示_文明放大镜·7 | 清新智能语音提示桩让你过马路除了看灯还可以听,赞...
- C#调用windows API实现 smallpdf客户端程序进行批量压缩
- python常用模块初始
- 查看Eclipse版本号,及各个版本区别
- 交易系统开发(四)——交易柜台系统
- 软件观念革命:交互设计精髓_电子沙盘设计主要分为哪几种?
- 第六章第三十题(游戏:双骰子赌博)(Game: craps)
- [ZZ]为什么选择傲游
- USYD悉尼大学DATA1002 详细作业解析Module3
- btcTrade_project
- linux startx无效_startx启动图形界面失败的几个解决方法
- RenderScript 让你的Android计算速度快的飞上天!
热门文章
- LAMP搭建Discuz论坛(腾讯云环境)
- slam入门3:2D-2D对极几何中的对极约束公式详细解释(参考 视觉slam十四讲)
- python合并多个csv文件为excel并绘制曲线(参考文章记录)
- Android 最丝滑的动画--第二篇MotionLayout概述(后面陆续更新)(带效果图)
- php中函数trim,PHP trim()函数
- 威纶通触摸屏模板,直接打开就可以用 威纶通触摸屏,全部图库
- 卡夫曼自适应移动均线交易系统
- 卸载eigen库正确方式
- 人工智能辅助筛查肺癌 帮医生减负,缓和医患矛盾
- 霍夫变换实现球体追踪opencv