Spring与SpringBoot

1、Spring能做什么

1.1、Spring的能力

SpringBoot2 - 图1

1.2、Spring的生态

https://spring.io/projects/spring-boot

覆盖了:

web开发

数据访问

安全控制

分布式

消息服务

移动开发

批处理

……

1.3、Spring5重大升级

1.3.1、响应式编程

SpringBoot2 - 图2

1.3.2、内部源码设计

基于Java8的一些新特性,如:接口默认实现。重新设计源码架构。

2、为什么用SpringBoot

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

能快速创建出生产级别的Spring应用

2.1、SpringBoot优点

  • Create stand-alone Spring applications
    • 创建独立Spring应用
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
    • 内嵌web服务器
  • Provide opinionated ‘starter’ dependencies to simplify your build configuration
    • 自动starter依赖,简化构建配置
  • Automatically configure Spring and 3rd party libraries whenever possible
    • 自动配置Spring以及第三方功能
  • Provide production-ready features such as metrics, health checks, and externalized configuration
    • 提供生产级别的监控、健康检查及外部化配置
  • Absolutely no code generation and no requirement for XML configuration
    • 无代码生成、无需编写XML

SpringBoot是整合Spring技术栈的一站式框架

SpringBoot是简化Spring技术栈的快速开发脚手架

2.2、SpringBoot缺点

  • 人称版本帝,迭代快,需要时刻关注变化
  • 封装太深,内部原理复杂,不容易精通

3、时代背景

3.1、微服务

James Lewis and Martin Fowler (2014) 提出微服务完整概念。https://martinfowler.com/microservices/

In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.— James Lewis and Martin Fowler (2014)

  • 微服务是一种架构风格
  • 一个应用拆分为一组小型服务
  • 每个服务运行在自己的进程内,也就是可独立部署和升级
  • 服务之间使用轻量级HTTP交互
  • 服务围绕业务功能拆分
  • 可以由全自动部署机制独立部署
  • 去中心化,服务自治。服务可以使用不同的语言、不同的存储技术

3.2、分布式

SpringBoot2 - 图3

分布式的困难

  • 远程调用
  • 服务发现
  • 负载均衡
  • 服务容错
  • 配置管理
  • 服务监控
  • 链路追踪
  • 日志管理
  • 任务调度
  • ……

分布式的解决

  • SpringBoot + SpringCloud

SpringBoot2 - 图4

3.3、云原生

原生应用如何上云。 Cloud Native

上云的困难

  • 服务自愈
  • 弹性伸缩
  • 服务隔离
  • 自动化部署
  • 灰度发布
  • 流量治理
  • ……

上云的解决

SpringBoot2 - 图5

4、如何学习SpringBoot

4.1、官网文档架构

SpringBoot2 - 图6

SpringBoot2 - 图7

查看版本新特性;

https://github.com/spring-projects/spring-boot/wiki#release-notes

SpringBoot2 - 图8

SpringBoot2入门

1、系统要求

  • Java 8 & 兼容java14 .
  • Maven 3.3+
  • idea 2019.1.2

1.1、maven设置

  1. <mirrors>
  2. <mirror>
  3. <id>nexus-aliyun</id>
  4. <mirrorOf>central</mirrorOf>
  5. <name>Nexus aliyun</name>
  6. <url>http://maven.aliyun.com/nexus/content/groups/public</url>
  7. </mirror>
  8. </mirrors>
  9. <profiles>
  10. <profile>
  11. <id>jdk-1.8</id>
  12. <activation>
  13. <activeByDefault>true</activeByDefault>
  14. <jdk>1.8</jdk>
  15. </activation>
  16. <properties>
  17. <maven.compiler.source>1.8</maven.compiler.source>
  18. <maven.compiler.target>1.8</maven.compiler.target>
  19. <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
  20. </properties>
  21. </profile>
  22. </profiles>

2、HelloWorld

需求:浏览发送/hello请求,响应 Hello,Spring Boot 2

2.1、创建maven工程

2.2、引入依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.4.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. </dependencies>

2.3、创建主程序

  1. /**
  2. * 主程序类
  3. * @SpringBootApplication:这是一个SpringBoot应用
  4. */
  5. @SpringBootApplication
  6. public class MainApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(MainApplication.class,args);
  9. }
  10. }

2.4、编写业务

  1. @RestController
  2. public class HelloController {
  3. @RequestMapping("/hello")
  4. public String handle01(){
  5. return "Hello, Spring Boot 2!";
  6. }
  7. }

2.5、测试

直接运行main方法

2.6、简化配置

application.properties

  1. server.port=8888

2.7、简化部署

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. </plugin>
  7. </plugins>
  8. </build>

把项目打成jar包,直接在目标服务器执行即可。

注意点:

  • 取消掉cmd的快速编辑模式

自动配置原理

1、SpringBoot特点

1.1、依赖管理

  • 父项目做依赖管理
  1. 依赖管理
  2. <parent>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-parent</artifactId>
  5. <version>2.3.4.RELEASE</version>
  6. </parent>
  7. 他的父项目
  8. <parent>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-dependencies</artifactId>
  11. <version>2.3.4.RELEASE</version>
  12. </parent>
  13. 几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter</artifactId>
  4. <version>2.3.4.RELEASE</version>
  5. <scope>compile</scope>
  6. </dependency>
  1. 场景依赖例图:

SpringBoot2 - 图9

  • 无需关注版本号,自动版本仲裁
    1、引入依赖默认都可以不写版本
    2、引入非版本仲裁的jar,要写版本号
  • 可以修改默认版本号
    1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
    2、在当前项目里面重写配置
  1. <properties>
  2. <mysql.version>5.1.43</mysql.version>
  3. </properties>

1.2、自动配置

  • 自动配好Tomcat
    • 引入Tomcat依赖。
    • 配置Tomcat
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-tomcat</artifactId>
  4. <version>2.3.4.RELEASE</version>
  5. <scope>compile</scope>
  6. </dependency>
  • 自动配好SpringMVC
    • 引入SpringMVC全套组件
    • 自动配好SpringMVC常用组件(功能)
  • 自动配好Web常见功能,如:字符编码问题
    • SpringBoot帮我们配置好了所有web开发的常见场景
  • 默认的包结构
    • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
    • 无需以前的包扫描配置
    • 想要改变扫描路径
      • @SpringBootApplication(scanBasePackages=“com.atguigu”)
  1. @SpringBootApplication
  2. 等同于
  3. @SpringBootConfiguration
  4. @EnableAutoConfiguration
  5. @ComponentScan("com.atguigu.boot")
  • 各种配置拥有默认值
    • 默认配置最终都是映射到某个类上,如:MultipartProperties
    • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
  • 按需加载所有自动配置项
    • 非常多的starter
    • 引入了哪些场景这个场景的自动配置才会开启
    • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面
  • ……

2、容器功能

2.1、组件添加

1、@Configuration

  • 基本使用
  • Full模式与Lite模式
    • 示例
    • 最佳实战
    • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
    • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
    • bean类:
    • ```java package boot.bean;

public class User { private String userName; private int age; private Pet pet;

  1. public User() {
  2. }
  3. public User(String userName, int age, Pet pet) {
  4. this.userName = userName;
  5. this.age = age;
  6. this.pet = pet;
  7. }
  8. public Pet getPet() {
  9. return pet;
  10. }
  11. public void setPet(Pet pet) {
  12. this.pet = pet;
  13. }
  14. public String getUserName() {
  15. return userName;
  16. }
  17. public void setUserName(String userName) {
  18. this.userName = userName;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. public void setAge(int age) {
  24. this.age = age;
  25. }
  26. @Override
  27. public String toString() {
  28. return "User{" +
  29. "userName='" + userName + '\'' +
  30. ", age=" + age +
  31. ", pet=" + pet +
  32. '}';
  33. }

}

  1. -
  2. ```java
  3. package boot.bean;
  4. public class Pet {
  5. private String petName;
  6. public Pet(String petName) {
  7. this.petName = petName;
  8. }
  9. public Pet() {
  10. }
  11. public String getPetName() {
  12. return petName;
  13. }
  14. public void setPetName(String petName) {
  15. this.petName = petName;
  16. }
  17. @Override
  18. public String toString() {
  19. return "Pet{" +
  20. "petName='" + petName + '\'' +
  21. '}';
  22. }
  23. }
  • 配置实例:
  • ```java Configuration使用示例 /**

    • 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
    • 2、配置类本身也是组件
    • 3、proxyBeanMethods:代理bean的方法
    • Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
    • Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
    • 组件依赖必须使用Full模式默认。其他默认是否Lite模式 / @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件 public class MyConfig {

    /**

    • Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
    • @return */ @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例 public User user01(){ User zhangsan = new User(“zhangsan”, 18); //user组件依赖了Pet组件 zhangsan.setPet(tomcatPet()); return zhangsan; }

    @Bean(“tom”)//定义个组件的id,而不是方法名 public Pet tomcatPet(){ return new Pet(“tomcat”); } }

    ##########################@Configuration测试代码如下

    @SpringBootApplication public class MainApplication {

    public static void main(String[] args) { //1、返回我们IOC容器 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

    //2、查看容器里面的组件 String[] names = run.getBeanDefinitionNames(); for (String name : names) {

    1. System.out.println(name);

    }

    //3、从容器中获取组件

    Pet tom01 = run.getBean(“tom”, Pet.class);

    Pet tom02 = run.getBean(“tom”, Pet.class);

    System.out.println(“组件:”+(tom01 == tom02));

  1. //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
  2. MyConfig bean = run.getBean(MyConfig.class);
  3. System.out.println(bean);
  4. //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
  5. //保持组件单实例
  6. User user = bean.user01();
  7. User user1 = bean.user01();
  8. System.out.println(user == user1);
  9. User user01 = run.getBean("user01", User.class);
  10. Pet tom = run.getBean("tom", Pet.class);
  11. System.out.println("用户的宠物:"+(user01.getPet() == tom));
  12. }

}

  1. <a name="2e4b1886"></a>
  2. #### 2、@Bean、@Component、@Controller、@Service、[@Repository ](/Repository )
  3. - spring已经讲过
  4. <a name="d01d2eda"></a>
  5. #### 3、@ComponentScan、[@Import ](/Import )
  6. - import用法: <br />验证注入的组件: <br />结果可知:boot.bean.User,newUser import创建的是全类名的组件
  7. ```java
  8. /*
  9. * @Import({User.class, DBHelper.class})
  10. * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
  11. */
  12. @Import({User.class, DBHelper.class})
  13. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  14. public class MyConfig {
  15. }
  1. //获取import导入组件的bean
  2. String[] users = run.getBeanNamesForType(User.class);
  3. for (String s : users) {
  4. System.out.println(s);
  5. }

4、@Conditional

  • 条件装配:满足Conditional指定的条件,则进行组件注入

SpringBoot2 - 图10

  1. =====================测试条件装配==========================
  2. @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
  3. //@ConditionalOnBean(name = "tom")
  4. @ConditionalOnMissingBean(name = "tom")
  5. public class MyConfig {
  6. /**
  7. * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
  8. * @return
  9. */
  10. @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
  11. // @ConditionalOnMissingBean(name="tom")
  12. public User user01(){
  13. User zhangsan = new User("zhangsan", 18);
  14. //user组件依赖了Pet组件
  15. zhangsan.setPet(tomcatPet());
  16. return zhangsan;
  17. }
  18. @Bean("tom22")
  19. public Pet tomcatPet(){
  20. return new Pet("tomcat");
  21. }
  22. }
  23. public static void main(String[] args) {
  24. //1、返回我们IOC容器
  25. ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
  26. //2、查看容器里面的组件
  27. String[] names = run.getBeanDefinitionNames();
  28. for (String name : names) {
  29. System.out.println(name);
  30. }
  31. boolean tom = run.containsBean("tom");
  32. System.out.println("容器中Tom组件:"+tom);
  33. boolean user01 = run.containsBean("user01");
  34. System.out.println("容器中user01组件:"+user01);
  35. boolean tom22 = run.containsBean("tom22");
  36. System.out.println("容器中tom22组件:"+tom22);
  37. }

2.2、原生配置文件引入

@ImportResource
  • 可以引入配置文件,将配置文件组件自动注入IOC

    1. ======================beans.xml=========================
    2. <?xml version="1.0" encoding="UTF-8"?>
    3. <beans xmlns="http://www.springframework.org/schema/beans"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:context="http://www.springframework.org/schema/context"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    7. <bean id="haha" class="com.atguigu.boot.bean.User">
    8. <property name="name" value="zhangsan"></property>
    9. <property name="age" value="18"></property>
    10. </bean>
    11. <bean id="hehe" class="com.atguigu.boot.bean.Pet">
    12. <property name="name" value="tomcat"></property>
    13. </bean>
    14. </beans>

    ```java @ImportResource(“classpath:beans.xml”) public class MyConfig {}

======================测试================= boolean haha = run.containsBean(“haha”); boolean hehe = run.containsBean(“hehe”); System.out.println(“haha:”+haha);//true System.out.println(“hehe:”+hehe);//true

  1. <a name="0da8b5a2"></a>
  2. #### 2.3、配置绑定
  3. - 如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;
  4. ```java
  5. public class getProperties {
  6. public static void main(String[] args) throws FileNotFoundException, IOException {
  7. Properties pps = new Properties();
  8. pps.load(new FileInputStream("a.properties"));
  9. Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
  10. while(enum1.hasMoreElements()) {
  11. String strKey = (String) enum1.nextElement();
  12. String strValue = pps.getProperty(strKey);
  13. System.out.println(strKey + "=" + strValue);
  14. //封装到JavaBean。
  15. }
  16. }
  17. }

springboot提供更简洁的注解方式

  • @ConfigurationProperties使用(@Component + @ConfigurationProperties)

    • 配置文件:

      1. mycar.brand=BMW
      2. mycar.price=1000000
    • Car类:
      ```java package boot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;

/**

  • 只有在容器中的组件,才会拥有SpringBoot提供的强大功能 */ @Component @ConfigurationProperties(prefix = “mycar”) public class Car { private String brand; public Integer price;

    public Car(String brand, Integer price) {

    1. this.brand = brand;
    2. this.price = price;

    }

    public Car() { }

    public String getBrand() {

    1. return brand;

    }

    public void setBrand(String brand) {

    1. this.brand = brand;

    }

    public Integer getPrice() {

    1. return price;

    }

    public void setPrice(Integer price) {

    1. this.price = price;

    }

    @Override public String toString() {

    1. return "Car{" +
    2. "brand='" + brand + '\'' +
    3. ", price=" + price +
    4. '}';

    } }

    1. - 在控制器类中可以自动获取
    2. ```java
    3. @RestController
    4. public class FirstController {
    5. @Autowired
    6. Car car;
    7. @RequestMapping("/car")
    8. public Car car(){
    9. return car;
    10. }
    11. }
  • @ConfigurationProperties使用(@EnableConfigurationProperties + @ConfigurationProperties)
    • 需要在配置类加入注解(在为第三方包的对象,无法使用@Component时可以使用)
      1. @EnableConfigurationProperties(Car.class)
      2. public class MyConfig {

3、自动配置原理入门

3.1、引导加载自动配置类

  1. @SpringBootConfiguration
  2. @EnableAutoConfiguration
  3. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
  4. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
  5. public @interface SpringBootApplication{}
  6. ======================

1、@SpringBootConfiguration

@Configuration。代表当前是一个配置类

2、@ComponentScan

指定扫描哪些,Spring注解;

3、@EnableAutoConfiguration

  1. @AutoConfigurationPackage
  2. @Import(AutoConfigurationImportSelector.class)
  3. public @interface EnableAutoConfiguration {}

1、@AutoConfigurationPackage

自动配置包?指定了默认的包规则

  1. @Import(AutoConfigurationPackages.Registrar.class) //给容器中导入一个组件
  2. public @interface AutoConfigurationPackage {}
  3. //利用Registrar给容器中导入一系列组件
  4. //将指定的一个包下的所有组件导入进来?MainApplication 所在包下。

2、@Import(AutoConfigurationImportSelector.class)
  1. 1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
  2. 2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
  3. 3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
  4. 4、从META-INF/spring.factories位置来加载一个文件。
  5. 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
  6. spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

SpringBoot2 - 图11

  1. 文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
  2. spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
  3. # Auto Configure
  4. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  5. org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
  6. org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
  7. org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
  8. org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
  9. org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
  10. org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
  11. org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
  12. org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
  13. org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
  14. org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
  15. org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
  16. org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
  17. org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
  18. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
  19. org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
  20. org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
  21. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
  22. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
  23. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
  24. org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
  25. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
  26. org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
  27. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
  28. org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
  29. org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  30. org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
  31. org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
  32. org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
  33. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
  34. org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
  35. org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
  36. org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
  37. org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
  38. org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
  39. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
  40. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
  41. org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
  42. org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
  43. org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
  44. org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
  45. org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
  46. org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
  47. org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
  48. org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
  49. org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
  50. org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
  51. org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
  52. org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
  53. org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
  54. org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
  55. org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
  56. org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
  57. org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
  58. org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
  59. org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
  60. org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
  61. org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
  62. org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  63. org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
  64. org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
  65. org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
  66. org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  67. org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
  68. org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
  69. org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
  70. org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
  71. org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
  72. org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
  73. org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
  74. org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
  75. org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
  76. org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
  77. org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
  78. org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
  79. org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
  80. org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
  81. org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
  82. org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
  83. org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
  84. org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
  85. org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
  86. org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
  87. org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
  88. org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
  89. org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
  90. org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
  91. org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
  92. org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
  93. org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
  94. org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
  95. org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
  96. org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
  97. org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
  98. org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
  99. org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
  100. org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
  101. org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
  102. org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
  103. org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
  104. org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
  105. org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
  106. org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
  107. org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
  108. org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
  109. org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
  110. org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
  111. org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
  112. org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
  113. org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
  114. org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
  115. org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
  116. org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
  117. org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
  118. org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
  119. org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
  120. org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
  121. org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
  122. org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
  123. org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
  124. org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
  125. org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
  126. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
  127. org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
  128. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
  129. org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
  130. org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
  131. org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3.2、按需开启自动配置项

  • 虽然我们127个场景的所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
    按照条件装配规则(@Conditional),最终会按需配置。

3.3、修改默认配置

  • 解析web一些配置:
  1. @Configuration(
  2. proxyBeanMethods = false
  3. )
  4. @Conditional({DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition.class})
  5. //包含此类的组件则实行下面的方法
  6. @ConditionalOnClass({ServletRegistration.class})
  7. //1.将配置文件与组件绑定2.在注入到配置文件
  8. @EnableConfigurationProperties({WebMvcProperties.class})
  9. protected static class DispatcherServletConfiguration {
  10. protected DispatcherServletConfiguration() {
  11. }
  12. @Bean(
  13. name = {"dispatcherServlet"}
  14. )
  15. //不用在手动的配置DispatcherServlet,springboot会new一个,并返回
  16. public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) {
  17. DispatcherServlet dispatcherServlet = new DispatcherServlet();
  18. dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());
  19. dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());
  20. dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());
  21. dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());
  22. dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails());
  23. return dispatcherServlet;
  24. }
  1. @Bean
  2. @ConditionalOnBean(MultipartResolver.class) //容器中有这个类型组件
  3. @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件,SpringBoot会才会自动配置,如果自己@Bean一个multipartResolver组件,就不会配置
  4. public MultipartResolver multipartResolver(MultipartResolver resolver) {
  5. //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
  6. //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
  7. // Detect if the user has created a MultipartResolver but named it incorrectly
  8. return resolver;
  9. }
  10. 给容器中加入了文件上传解析器;
  • SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先
  1. @Bean
  2. //不包含CharacterEncodingFilter会执行方法,自动创建
  3. @ConditionalOnMissingBean
  4. public CharacterEncodingFilter characterEncodingFilter() {
  5. CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
  6. filter.setEncoding(this.properties.getCharset().name());
  7. filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
  8. filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
  9. return filter;
  10. }
  1. @Bean
  2. @ConditionalOnMissingBean
  3. public CharacterEncodingFilter characterEncodingFilter() {
  4. }

总结

  • SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
  • 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
  • 生效的配置类就会给容器中装配很多组件
  • 只要容器中有这些组件,相当于这些功能就有了
  • 定制化配置
    • 用户直接自己@Bean替换底层的组件
    • 用户去看这个组件是获取的配置文件什么值就去修改。

xxxxxAutoConfiguration —-> 组件 —-> xxxxProperties里面拿值 ——> application.properties

3.4、最佳实践

4、开发小技巧

4.1、Lombok

  • 简化JavaBean开发
    idea中搜索安装lombok插件

    1. <dependency>
    2. <groupId>org.projectlombok</groupId>
    3. <artifactId>lombok</artifactId>
    4. </dependency>

    ```java ===============================简化JavaBean开发=================================== @NoArgsConstructor //@AllArgsConstructor @Data @ToString @EqualsAndHashCode public class User {

    private String name; private Integer age;

    private Pet pet;

    public User(String name,Integer age){

    1. this.name = name;
    2. this.age = age;

    }

}

================================简化日志开发=================================== @Slf4j @RestController public class HelloController { @RequestMapping(“/hello”) public String handle01(@RequestParam(“name”) String name){

  1. log.info("请求进来了....");
  2. return "Hello, Spring Boot 2!"+"你好:"+name;
  3. }

}

  1. <a name="1c2f70d9"></a>
  2. ### 4.2、dev-tools
  3. ```xml
  4. <dependency>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-devtools</artifactId>
  7. <optional>true</optional>
  8. </dependency>

项目或者页面修改以后:Ctrl+F9;

4.3、Spring Initailizr(项目初始化向导)

0、选择我们需要的开发场景

SpringBoot2 - 图12

1、自动依赖引入

SpringBoot2 - 图13

2、自动创建项目结构

SpringBoot2 - 图14

3、自动编写好主配置类

SpringBoot2 - 图15

配置文件

1、文件类型

1.1、properties

同以前的properties用法

1.2、yaml

1.2.1、简介

YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:”Yet Another Markup Language”(仍是一种标记语言)。

非常适合用来做以数据为中心的配置文件

1.2.2、基本语法

  • key: value;kv之间有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • ‘#’表示注释
  • 字符串无需加引号,如果要加,’’与””表示字符串内容 会被 转义/不转义

1.2.3、数据类型

  • 字面量:单个的、不可再分的值。date、boolean、string、number、null
  1. k: v
  • 对象:键值对的集合。map、hash、set、object
  1. 行内写法: k: {k1:v1,k2:v2,k3:v3}
  2. #或
  3. k:
  4. k1: v1
  5. k2: v2
  6. k3: v3
  • 数组:一组按次序排列的值。array、list、queue
  1. 行内写法: k: [v1,v2,v3]
  2. #或者
  3. k:
  4. - v1
  5. - v2
  6. - v3

1.2.4、示例

  1. @Data
  2. public class Person {
  3. private String userName;
  4. private Boolean boss;
  5. private Date birth;
  6. private Integer age;
  7. private Pet pet;
  8. private String[] interests;
  9. private List<String> animal;
  10. private Map<String, Object> score;
  11. private Set<Double> salarys;
  12. private Map<String, List<Pet>> allPets;
  13. }
  14. @Data
  15. public class Pet {
  16. private String name;
  17. private Double weight;
  18. }
  1. # yaml表示以上对象
  2. person:
  3. #单引号会将 \n 作为字符串输出 双引号会将\n作为换行输出
  4. #双引号不会转义,单引号会转义
  5. userName: zhangsan
  6. boss: false
  7. birth: 2019/12/12 20:12:33
  8. age: 18
  9. pet:
  10. name: tomcat
  11. weight: 23.4
  12. interests: [篮球,游泳]
  13. animal:
  14. - jerry
  15. - mario
  16. score:
  17. english:
  18. first: 30
  19. second: 40
  20. third: 50
  21. math: [131,140,148]
  22. chinese: {first: 128,second: 136}
  23. salarys: [3999,4999.98,5999.99]
  24. allPets:
  25. sick:
  26. - {name: tom}
  27. - {name: jerry,weight: 47}
  28. health: [{name: mario,weight: 47}]

注意:使用yml时报

SpringBoot2 - 图16

导入依赖:(编写时有提示)

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>

2、配置提示

自定义的类和配置文件绑定一般没有提示。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-configuration-processor</artifactId>
  4. <optional>true</optional>
  5. </dependency>
  6. <build>
  7. <plugins>
  8. <plugin>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-maven-plugin</artifactId>
  11. <configuration>
  12. <excludes>
  13. <exclude>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-configuration-processor</artifactId>
  16. </exclude>
  17. </excludes>
  18. </configuration>
  19. </plugin>
  20. </plugins>
  21. </build>

Web开发

SpringBoot2 - 图17

1、SpringMVC自动配置概览

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)

The auto-configuration adds the following features on top of Spring’s defaults:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
    • 内容协商视图解析器和BeanName视图解析器
  • Support for serving static resources, including support for WebJars (covered later in this document)).
    • 静态资源(包括webjars)
  • Automatic registration of Converter, GenericConverter, and Formatter beans.
    • 自动注册 Converter,GenericConverter,Formatter
  • Support for HttpMessageConverters (covered later in this document).
    • 支持 HttpMessageConverters (后来我们配合内容协商理解原理)
  • Automatic registration of MessageCodesResolver (covered later in this document).
    • 自动注册 MessageCodesResolver (国际化用)
  • Static index.html support.
    • 静态index.html 页支持
  • Custom Favicon support (covered later in this document).
    • 自定义 Favicon
  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
    • 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

不用@EnableWebMvc注解。使用 **@Configuration** + **WebMvcConfigurer** 自定义规则

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

声明 **WebMvcRegistrations** 改变默认底层组件

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

使用 **@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC**

2、简单功能分析

2.1、静态资源访问

1、静态资源目录

只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources

访问 : 当前项目根路径/ + 静态资源名

原理: 静态映射/**

请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

改变默认的静态资源路径

  1. spring:
  2. mvc:
  3. static-path-pattern: /res/**
  4. web:
  5. resources:
  6. static-locations: [classpath:/haha/] //classpath后面没空格

2、静态资源访问前缀

默认无前缀

  1. spring:
  2. mvc:
  3. static-path-pattern: /res/**

当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下找

3、webjar

自动映射 /webjars/**

https://www.webjars.org/

  1. <dependency>
  2. <groupId>org.webjars</groupId>
  3. <artifactId>jquery</artifactId>
  4. <version>3.5.1</version>
  5. </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

2.2、欢迎页支持

  • 静态资源路径下 index.html
    • 可以配置静态资源路径
    • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
  1. spring:
  2. # mvc:
  3. # static-path-pattern: /res/** 这个会导致welcome page功能失效
  4. resources:
  5. static-locations: [classpath:/haha/]
  • controller能处理/index

2.3、自定义 Favicon

favicon.ico 放在静态资源目录下即可。

  1. spring:
  2. # mvc:
  3. # static-path-pattern: /res/** 这个会导致 Favicon 功能失效

2.4、静态资源配置原理

  • SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
  • SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效
  1. @Configuration(proxyBeanMethods = false)
  2. @ConditionalOnWebApplication(type = Type.SERVLET)
  3. @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
  4. @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
  5. @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
  6. @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
  7. ValidationAutoConfiguration.class })
  8. public class WebMvcAutoConfiguration {}
  • 给容器中配了什么。
  1. @Configuration(proxyBeanMethods = false)
  2. @Import(EnableWebMvcConfiguration.class)
  3. @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
  4. @Order(0)
  5. public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
  • 配置文件的相关属性和xxx进行了绑定。WebMvcProperties==spring.mvc、ResourceProperties==spring.resources

1、配置类只有一个有参构造器

  1. //有参构造器所有参数的值都会从容器中确定
  2. //ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
  3. //WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
  4. //ListableBeanFactory beanFactory Spring的beanFactory
  5. //HttpMessageConverters 找到所有的HttpMessageConverters
  6. //ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
  7. //DispatcherServletPath
  8. //ServletRegistrationBean 给应用注册Servlet、Filter....
  9. public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
  10. ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
  11. ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
  12. ObjectProvider<DispatcherServletPath> dispatcherServletPath,
  13. ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
  14. this.resourceProperties = resourceProperties;
  15. this.mvcProperties = mvcProperties;
  16. this.beanFactory = beanFactory;
  17. this.messageConvertersProvider = messageConvertersProvider;
  18. this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
  19. this.dispatcherServletPath = dispatcherServletPath;
  20. this.servletRegistrations = servletRegistrations;
  21. }

2、资源处理的默认规则

  1. @Override
  2. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  3. if (!this.resourceProperties.isAddMappings()) {
  4. logger.debug("Default resource handling disabled");
  5. return;
  6. }
  7. Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
  8. CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
  9. //webjars的规则
  10. if (!registry.hasMappingForPattern("/webjars/**")) {
  11. customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
  12. .addResourceLocations("classpath:/META-INF/resources/webjars/")
  13. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  14. }
  15. //
  16. String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  17. if (!registry.hasMappingForPattern(staticPathPattern)) {
  18. customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
  19. .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
  20. .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
  21. }
  22. }
  23. spring:
  24. # mvc:
  25. # static-path-pattern: /res/**
  26. resources:
  27. add-mappings: false 禁用所有静态资源规则
  28. @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
  29. public class ResourceProperties {
  30. private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
  31. "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
  32. /**
  33. * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
  34. * /resources/, /static/, /public/].
  35. */
  36. private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

3、欢迎页的处理规则

  1. HandlerMapping:处理器映射。保存了每一个Handler能处理哪些请求。
  2. @Bean
  3. public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
  4. FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
  5. WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
  6. new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
  7. this.mvcProperties.getStaticPathPattern());
  8. welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
  9. welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
  10. return welcomePageHandlerMapping;
  11. }
  12. WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
  13. ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
  14. if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
  15. //要用欢迎页功能,必须是/**
  16. logger.info("Adding welcome page: " + welcomePage.get());
  17. setRootViewName("forward:index.html");
  18. }
  19. else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
  20. // 调用Controller /index
  21. logger.info("Adding welcome page template: index");
  22. setRootViewName("index");
  23. }
  24. }

4、favicon

  • 浏览器会发送/favicon.ioc请求获取到图标,整个session期间不再获取

3、请求参数处理

请求映射

1、rest使用与原理

  • @xxxMapping;
  • Rest风格支持(使用HTTP请求方式动词来表示对资源的操作
    • 以前:*/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户
    • 现在: /user GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户
    • 核心Filter;HiddenHttpMethodFilter
      • 用法: 表单method=post,隐藏域 _method=put
      • SpringBoot中手动开启
    • 扩展:如何把_method 这个名字换成我们自己喜欢的。
    • 测试:
  • ```java @RequestMapping(value = “/user”,method = RequestMethod.GET) public String getUser(){

    1. return "GET-张三";

    }

    @RequestMapping(value = “/user”,method = RequestMethod.POST) public String saveUser(){

    1. return "POST-张三";

    }

  1. @RequestMapping(value = "/user",method = RequestMethod.PUT)
  2. public String putUser(){
  3. return "PUT-张三";
  4. }
  5. @RequestMapping(value = "/user",method = RequestMethod.DELETE)
  6. public String deleteUser(){
  7. return "DELETE-张三";
  8. }
  9. @Bean
  10. @ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
  11. @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
  12. public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
  13. return new OrderedHiddenHttpMethodFilter();
  14. }

//自定义filter @Bean public HiddenHttpMethodFilter hiddenHttpMethodFilter(){ HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter(); methodFilter.setMethodParam(“_m”); return methodFilter; }

  1. -
  2. ```html
  3. 测试REST风格;
  4. <form action="/user" method="get">
  5. <input value="REST-GET 提交" type="submit"/>
  6. </form>
  7. <form action="/user" method="post">
  8. <input value="REST-POST 提交" type="submit"/>
  9. </form>
  10. <form action="/user" method="post">
  11. <input name="_method" type="hidden" value="delete"/>
  12. <input name="_m" type="hidden" value="delete"/>
  13. <input value="REST-DELETE 提交" type="submit"/>
  14. </form>
  15. <form action="/user" method="post">
  16. <input name="_method" type="hidden" value="PUT"/>
  17. <input value="REST-PUT 提交" type="submit"/>
  18. </form>
  19. <hr/>
  • Rest原理(表单提交要使用REST的时候)

      1. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      2. HttpServletRequest requestToUse = request;
      3. if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
      4. String paramValue = request.getParameter(this.methodParam);
      5. if (StringUtils.hasLength(paramValue)) {
      6. //会将请求都转化为大写,因此小写不影响
      7. String method = paramValue.toUpperCase(Locale.ENGLISH);
      8. if (ALLOWED_METHODS.contains(method)) {
      9. requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
      10. }
      11. }
      12. }
      13. //将包装后的requesWrapper放行
      14. filterChain.doFilter((ServletRequest)requestToUse, response);
      15. }
    • 表单提交会带上_method=PUT

    • 请求过来被HiddenHttpMethodFilter拦截
      • 请求是否正常,并且是POST
        • 获取到_method的值。
        • 兼容以下请求;PUT.DELETE.PATCH
        • 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
          ```java //是原生的selevet,并重写了getMethod private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper { private final String method;

      public HttpMethodRequestWrapper(HttpServletRequest request, String method) { super(request); this.method = method; }

      public String getMethod() { return this.method; } }

      1. - **过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。**
      2. -
      3. ```yml
      4. spring:
      5. mvc:
      6. hiddenmethod:
      7. filter:
      8. enabled: true #开启页面表单的Rest功能
  • Rest使用客户端工具

    • 如PostMan直接发送Put、delete等方式请求,无需Filter。
  • 如何把_method字段改成我们喜欢的

    • 自己注入一个组件

      1. @Configuration(proxyBeanMethods = false)
      2. public class WebConfig /*implements WebMvcConfigurer*/ {
      3. @Bean
      4. public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
      5. HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
      6. methodFilter.setMethodParam("_m");
      7. return methodFilter;
      8. }
      9. }

2、请求映射原理

SpringBoot2 - 图18

SpringMVC功能分析都从 org.springframework.web.servlet.DispatcherServlet-》doDispatch()

  1. protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. HttpServletRequest processedRequest = request;
  3. HandlerExecutionChain mappedHandler = null;
  4. boolean multipartRequestParsed = false;
  5. WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
  6. try {
  7. ModelAndView mv = null;
  8. Exception dispatchException = null;
  9. try {
  10. processedRequest = checkMultipart(request);
  11. multipartRequestParsed = (processedRequest != request);
  12. // 找到当前请求使用哪个Handler(Controller的方法)处理
  13. mappedHandler = getHandler(processedRequest);
  14. //HandlerMapping:处理器映射。/xxx->>xxxx

SpringBoot2 - 图19

RequestMappingHandlerMapping:保存了所有@RequestMapping 和handler的映射规则。

SpringBoot2 - 图20

所有的请求映射都在HandlerMapping中。

  • SpringBoot自动配置欢迎页的 WelcomePageHandlerMapping 。访问 /能访问到index.html;
  • SpringBoot自动配置了默认 的 RequestMappingHandlerMapping
  • 请求进来,挨个尝试所有的HandlerMapping看是否有请求信息。
    • 如果有就找到这个请求对应的handler
      已经找到DELETE的Handler
      SpringBoot2 - 图21
    • 如果没有就是下一个 HandlerMapping
  • 我们需要一些自定义的映射处理,我们也可以自己给容器中放HandlerMapping。自定义 HandlerMapping
  1. @Nullable
  2. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
  3. if (this.handlerMappings != null) {
  4. Iterator var2 = this.handlerMappings.iterator();
  5. while(var2.hasNext()) {
  6. HandlerMapping mapping = (HandlerMapping)var2.next();
  7. HandlerExecutionChain handler = mapping.getHandler(request);
  8. if (handler != null) {
  9. return handler;
  10. }
  11. }
  12. }
  13. return null;
  14. }

普通参数与基本注解

1.1、注解:

  • @PathVariable、@RequestHeader、@ModelAttribute、@RequestParam、@MatrixVariable、@CookieValue、@RequestBody
    ```java @RestController public class ParameterTestController {
  1. // car/2/owner/zhangsan
  2. @GetMapping("/car/{id}/owner/{username}")
  3. public Map<String,Object> getCar(@PathVariable("id") Integer id,
  4. @PathVariable("username") String name,
  5. @PathVariable Map<String,String> pv,
  6. @RequestHeader("User-Agent") String userAgent,
  7. @RequestHeader Map<String,String> header,
  8. @RequestParam("age") Integer age,
  9. @RequestParam("inters") List<String> inters,
  10. @RequestParam Map<String,String> params,
  11. @CookieValue("_ga") String _ga,
  12. @CookieValue("_ga") Cookie cookie){
  13. Map<String,Object> map = new HashMap<>();

// map.put(“id”,id); // map.put(“name”,name); // map.put(“pv”,pv); // map.put(“userAgent”,userAgent); // map.put(“headers”,header); map.put(“age”,age); map.put(“inters”,inters); map.put(“params”,params); map.put(“_ga”,_ga); System.out.println(cookie.getName()+”===>”+cookie.getValue()); return map; }

  1. @PostMapping("/save")
  2. public Map postMethod(@RequestBody String content){
  3. Map<String,Object> map = new HashMap<>();
  4. map.put("content",content);
  5. return map;
  6. }
  7. //1、语法: 请求路径:/cars/sell;low=34;brand=byd,audi,yd
  8. //2、SpringBoot默认是禁用了矩阵变量的功能
  9. // 手动开启:原理。对于路径的处理。UrlPathHelper进行解析。
  10. // removeSemicolonContent(移除分号内容)支持矩阵变量的
  11. //再配置类中配置
  12. @Bean
  13. public WebMvcConfigurer webMvcConfigurer() {
  14. return new WebMvcConfigurer() {
  15. @Override
  16. public void configurePathMatch(PathMatchConfigurer configurer) {
  17. UrlPathHelper urlPathHelper = new UrlPathHelper();
  18. //不溢出;后面的内容,矩阵变量功能就可以生效
  19. urlPathHelper.setRemoveSemicolonContent(false);
  20. configurer.setUrlPathHelper(urlPathHelper);
  21. }
  22. };
  23. }
  24. //3、矩阵变量必须有url路径变量才能被解析
  25. @GetMapping("/cars/{path}")
  26. public Map carsSell(@MatrixVariable("low") Integer low,
  27. @MatrixVariable("brand") List<String> brand,
  28. @PathVariable("path") String path){
  29. Map<String,Object> map = new HashMap<>();
  30. map.put("low",low);
  31. map.put("brand",brand);
  32. map.put("path",path);
  33. return map;
  34. }
  35. // /boss/1;age=20/2;age=10
  36. @GetMapping("/boss/{bossId}/{empId}")
  37. public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
  38. @MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
  39. Map<String,Object> map = new HashMap<>();
  40. map.put("bossAge",bossAge);
  41. map.put("empAge",empAge);
  42. return map;
  43. }

}

  1. <a name="2bffb82f"></a>
  2. ## 5、视图解析与模板引擎
  3. - 视图解析:**SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。**
  4. <a name="44c30e47"></a>
  5. ### 1、视图解析
  6. ![](https://gitee.com/ljlGitee001/pictures/raw/master/img/202203112221522.png#crop=0&crop=0&crop=1&crop=1&id=WQn1t&originHeight=264&originWidth=516&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  7. <a name="b3068996"></a>
  8. #### 1、视图解析原理流程
  9. 1、目标方法处理的过程中,所有数据都会被放在 **ModelAndViewContainer 里面。包括数据和视图地址**
  10. **2、方法的参数是一个自定义类型对象(从请求参数中确定的),把他重新放在** **ModelAndViewContainer**
  11. **3、任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。**
  12. **4、processDispatchResult 处理派发结果(页面改如何响应)**
  13. - 1、**render**(**mv**, request, response); 进行页面渲染逻辑
  14. -
  15. - 1、根据方法的String返回值得到 **View** 对象【定义了页面的渲染逻辑】
  16. -
  17. -
  18. - 1、所有的视图解析器尝试是否能根据当前返回值得到**View**对象
  19. - 2、得到了 **redirect:/main.html** --> Thymeleaf new **RedirectView**()
  20. -
  21. -
  22. - 3、ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。
  23. - 4、view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作
  24. -
  25. -
  26. -
  27. - **RedirectView 如何渲染【重定向到一个页面】**
  28. - **1、获取目标url地址**
  29. -
  30. -
  31. -
  32. - **2、response.sendRedirect(encodedURL);**
  33. **视图解析:**
  34. -
  35. - **返回值以 forward: 开始: new InternalResourceView(forwardUrl); --> 转发request.getRequestDispatcher(path).forward(request, response);**
  36. - **返回值以** **redirect: 开始:** **new RedirectView() --》 render就是重定向**
  37. -
  38. - **返回值是普通字符串: new ThymeleafView()--->**
  39. 自定义视图解析器+自定义视图; **大厂学院。**
  40. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1605680247945-088b0f17-185c-490b-8889-103e8b4d8c07.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_16%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&id=I1FT5&originHeight=136&originWidth=577&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  41. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1605680247945-088b0f17-185c-490b-8889-103e8b4d8c07.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_16%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&id=voAK2&originHeight=136&originWidth=577&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  42. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1605679959020-54b96fe7-f2fc-4b4d-a392-426e1d5413de.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_23%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&id=ngvWr&originHeight=197&originWidth=824&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  43. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1605679471537-7db702dc-b165-4dc6-b64a-26459ee5fd6c.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_17%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&id=d7NKD&originHeight=217&originWidth=590&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  44. ![](https://cdn.nlark.com/yuque/0/2020/png/1354552/1605679913592-151a616a-c754-4da3-a2c1-91dc0230a48d.png?x-oss-process=image%2Fwatermark%2Ctype_d3F5LW1pY3JvaGVp%2Csize_22%2Ctext_YXRndWlndS5jb20g5bCa56GF6LC3%2Ccolor_FFFFFF%2Cshadow_50%2Ct_80%2Cg_se%2Cx_10%2Cy_10#crop=0&crop=0&crop=1&crop=1&id=tJ2NZ&originHeight=317&originWidth=764&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  45. <a name="680ecbd2"></a>
  46. ### 2、模板引擎-Thymeleaf
  47. <a name="8be32646"></a>
  48. #### 1、thymeleaf简介
  49. - Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.
  50. - **现代化、服务端Java模板引擎**
  51. <a name="25e14243"></a>
  52. #### 2、基本语法
  53. <a name="15d35776"></a>
  54. ##### 1、表达式
  55. | 表达式名字 | 语法 | 用途 |
  56. | --- | --- | --- |
  57. | 变量取值 | ${...} | 获取请求域、session域、对象等值 |
  58. | 选择变量 | *{...} | 获取上下文对象值 |
  59. | 消息 | #{...} | 获取国际化等值 |
  60. | 链接 | @{...} | 生成链接 |
  61. | 片段表达式 | ~{...} | jsp:include 作用,引入公共页面片段 |
  62. <a name="366dca5b"></a>
  63. ##### 2、字面量
  64. - 文本值: **'one text'** **,** **'Another one!'** **,…**数字: **0** **,** **34** **,** **3.0** **,** **12.3** **,…**布尔值: **true** **,** **false**
  65. - 空值: **null**
  66. - 变量: one,two,.... 变量不能有空格
  67. <a name="747ebdd0"></a>
  68. ##### 3、文本操作
  69. - 字符串拼接: **+**
  70. - 变量替换: **|The name is ${name}|**
  71. <a name="fc4eaaf9"></a>
  72. ##### 4、数学运算
  73. - 运算符: + , - , * , / , %
  74. <a name="17e851c3"></a>
  75. ##### 5、布尔运算
  76. - 运算符: **and** **,** **or**
  77. - 一元运算: **!** **,** **not**
  78. <a name="ee3b4091"></a>
  79. ##### 6、比较运算
  80. - 比较: **>** **,** **<** **,** **>=** **,** **<=** **(** **gt** **,** **lt** **,** **ge** **,** **le** **)**等式: **==** **,** **!=** **(** **eq** **,** **ne** **)**
  81. <a name="4252a13f"></a>
  82. ##### 7、条件运算
  83. - If-then: **(if) ? (then)**
  84. - If-then-else: **(if) ? (then) : (else)**
  85. - Default: (value) **?: (defaultvalue)**
  86. <a name="2624a096"></a>
  87. ##### 8、特殊操作
  88. - 无操作: _
  89. <a name="fed8d207"></a>
  90. #### 3、设置属性值-th:attr
  91. - 设置单个值
  92. ```html
  93. <form action="subscribe.html" th:attr="action=@{/subscribe}">
  94. <fieldset>
  95. <input type="text" name="email" />
  96. <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  97. </fieldset>
  98. </form>
  • 设置多个值
  1. <img src="../../images/gtvglogo.png" th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
  • 以上两个的代替写法 th:xxxx
  1. <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
  2. <form action="subscribe.html" th:action="@{/subscribe}">

所有h5兼容的标签写法

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

4、迭代

  1. <tr th:each="prod : ${prods}">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>
  1. <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
  2. <td th:text="${prod.name}">Onions</td>
  3. <td th:text="${prod.price}">2.41</td>
  4. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  5. </tr>

5、条件运算

  1. <a href="comments.html"
  2. th:href="@{/product/comments(prodId=${prod.id})}"
  3. th:if="${not #lists.isEmpty(prod.comments)}">view</a>
  1. <div th:switch="${user.role}">
  2. <p th:case="'admin'">User is an administrator</p>
  3. <p th:case="#{roles.manager}">User is a manager</p>
  4. <p th:case="*">User is some other thing</p>
  5. </div>

6、属性优先级

SpringBoot2 - 图22

3、thymeleaf使用

1、引入Starter

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

2、自动配置好了thymeleaf

  1. @Configuration(proxyBeanMethods = false)
  2. @EnableConfigurationProperties(ThymeleafProperties.class)
  3. @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
  4. @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
  5. public class ThymeleafAutoConfiguration { }

自动配好的策略

  • 1、所有thymeleaf的配置值都在 ThymeleafProperties
  • 2、配置好了 SpringTemplateEngine
  • 3、配好了 ThymeleafViewResolver
  • 4、我们只需要直接开发页面
  1. public static final String DEFAULT_PREFIX = "classpath:/templates/";
  2. public static final String DEFAULT_SUFFIX = ".html"; //xxx.html

3、页面开发

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1 th:text="${msg}">哈哈</h1>
  9. <h2>
  10. <a href="www.atguigu.com" th:href="${link}">去百度</a> <br/>
  11. <a href="www.atguigu.com" th:href="@{link}">去百度2</a>
  12. </h2>
  13. </body>
  14. </html>
  1. package boot.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. @Controller
  6. public class TestController {
  7. @GetMapping("/hello")
  8. public String hello(Model model){
  9. model.addAttribute("link","http://www.baidu.com");
  10. model.addAttribute("msg","hello world!!!");
  11. return "success";
  12. }
  13. }

4、构建后台管理系统

1、项目创建

thymeleaf、web-starter、devtools、lombok

2、静态资源处理

自动配置好,我们只需要把所有静态资源放到 static 文件夹下

3、路径构建

th:action=”@{/login}”

4、模板抽取

th:insert/replace/include

5、页面跳转
  1. @PostMapping("/login")
  2. public String main(User user, HttpSession session, Model model){
  3. if(StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())){
  4. //把登陆成功的用户保存起来
  5. session.setAttribute("loginUser",user);
  6. //登录成功重定向到main.html; 重定向防止表单重复提交
  7. return "redirect:/main.html";
  8. }else {
  9. model.addAttribute("msg","账号密码错误");
  10. //回到登录页面
  11. return "login";
  12. }
  13. }

6、数据渲染
  1. @GetMapping("/dynamic_table")
  2. public String dynamic_table(Model model){
  3. //表格内容的遍历
  4. List<User> users = Arrays.asList(new User("zhangsan", "123456"),
  5. new User("lisi", "123444"),
  6. new User("haha", "aaaaa"),
  7. new User("hehe ", "aaddd"));
  8. model.addAttribute("users",users);
  9. return "table/dynamic_table";
  10. }
  11. <table class="display table table-bordered" id="hidden-table-info">
  12. <thead>
  13. <tr>
  14. <th>#</th>
  15. <th>用户名</th>
  16. <th>密码</th>
  17. </tr>
  18. </thead>
  19. <tbody>
  20. <tr class="gradeX" th:each="user,stats:${users}">
  21. <td th:text="${stats.count}">Trident</td>
  22. <td th:text="${user.userName}">Internet</td>
  23. <td >[[${user.password}]]</td>
  24. </tr>
  25. </tbody>
  26. </table>

6、拦截器

1、HandlerInterceptor 接口

  1. /**
  2. * 登录检查
  3. * 1、配置好拦截器要拦截哪些请求
  4. * 2、把这些配置放在容器中
  5. */
  6. @Slf4j
  7. public class LoginInterceptor implements HandlerInterceptor {
  8. /**
  9. * 目标方法执行之前
  10. * @param request
  11. * @param response
  12. * @param handler
  13. * @return
  14. * @throws Exception
  15. */
  16. @Override
  17. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  18. String requestURI = request.getRequestURI();
  19. log.info("preHandle拦截的请求路径是{}",requestURI);
  20. //登录检查逻辑
  21. HttpSession session = request.getSession();
  22. Object loginUser = session.getAttribute("loginUser");
  23. if(loginUser != null){
  24. //放行
  25. return true;
  26. }
  27. //拦截住。未登录。跳转到登录页
  28. request.setAttribute("msg","请先登录");
  29. // re.sendRedirect("/");
  30. request.getRequestDispatcher("/").forward(request,response);
  31. return false;
  32. }
  33. /**
  34. * 目标方法执行完成以后
  35. * @param request
  36. * @param response
  37. * @param handler
  38. * @param modelAndView
  39. * @throws Exception
  40. */
  41. @Override
  42. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  43. log.info("postHandle执行{}",modelAndView);
  44. }
  45. /**
  46. * 页面渲染以后
  47. * @param request
  48. * @param response
  49. * @param handler
  50. * @param ex
  51. * @throws Exception
  52. */
  53. @Override
  54. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  55. log.info("afterCompletion执行异常{}",ex);
  56. }
  57. }

2、配置拦截器

  1. /**
  2. * 1、编写一个拦截器实现HandlerInterceptor接口
  3. * 2、拦截器注册到容器中(实现WebMvcConfigurer的addInterceptors)
  4. * 3、指定拦截规则【如果是拦截所有,静态资源也会被拦截】
  5. */
  6. @Configuration
  7. public class AdminWebConfig implements WebMvcConfigurer {
  8. @Override
  9. public void addInterceptors(InterceptorRegistry registry) {
  10. registry.addInterceptor(new LoginInterceptor())
  11. .addPathPatterns("/**") //所有请求都被拦截包括静态资源
  12. .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求
  13. }
  14. }

3、拦截器原理

1、根据当前请求,找到HandlerExecutionChain【可以处理请求的handler以及handler的所有 拦截器】

2、先来顺序执行 所有拦截器的 preHandle方法

  • 1、如果当前拦截器prehandler返回为true。则执行下一个拦截器的preHandle
  • 2、如果当前拦截器返回为false。直接 倒序执行所有已经执行了的拦截器的 afterCompletion;而为执行的拦截器则不执行afterCompletion

3、如果任何一个拦截器返回false。直接跳出不执行目标方法

4、所有拦截器都返回True。执行目标方法

5、倒序执行所有拦截器的postHandle方法。

6、前面的步骤有任何异常都会直接倒序触发 afterCompletion

7、页面成功渲染完成以后,也会倒序触发 afterCompletion

SpringBoot2 - 图23

  1. boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex = i++) {
  3. HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);
  4. if (!interceptor.preHandle(request, response, this.handler)) {
  5. this.triggerAfterCompletion(request, response, (Exception)null);
  6. return false;
  7. }
  8. }
  9. return true;
  10. }
  11. void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv) throws Exception {
  12. for(int i = this.interceptorList.size() - 1; i >= 0; --i) {
  13. HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);
  14. interceptor.postHandle(request, response, this.handler, mv);
  15. }
  16. }
  17. void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex) {
  18. for(int i = this.interceptorIndex; i >= 0; --i) {
  19. HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i);
  20. try {
  21. interceptor.afterCompletion(request, response, this.handler, ex);
  22. } catch (Throwable var7) {
  23. logger.error("HandlerInterceptor.afterCompletion threw exception", var7);
  24. }
  25. }

SpringBoot2 - 图24

7、文件上传

1、页面表单

  1. <form method="post" action="/upload" enctype="multipart/form-data">
  2. <input type="file" name="file"><br>
  3. <input type="submit" value="提交">
  4. </form>

2、文件上传代码

  1. /**
  2. * MultipartFile 自动封装上传过来的文件
  3. * @param email
  4. * @param username
  5. * @param headerImg
  6. * @param photos
  7. * @return
  8. */
  9. @PostMapping("/upload")
  10. public String upload(@RequestParam("email") String email,
  11. @RequestParam("username") String username,
  12. @RequestPart("headerImg") MultipartFile headerImg,
  13. @RequestPart("photos") MultipartFile[] photos) throws IOException {
  14. log.info("上传的信息:email={},username={},headerImg={},photos={}",
  15. email,username,headerImg.getSize(),photos.length);
  16. if(!headerImg.isEmpty()){
  17. //保存到文件服务器,OSS服务器
  18. String originalFilename = headerImg.getOriginalFilename();
  19. headerImg.transferTo(new File("H:\\cache\\"+originalFilename));
  20. }
  21. if(photos.length > 0){
  22. for (MultipartFile photo : photos) {
  23. if(!photo.isEmpty()){
  24. String originalFilename = photo.getOriginalFilename();
  25. photo.transferTo(new File("H:\\cache\\"+originalFilename));
  26. }
  27. }
  28. }
  29. return "main";
  30. }

3、application.properties中配置文件属性

  1. spring.servlet.multipart.max-file-size=10MB //单个文件最大限制
  2. spring.servlet.multipart.maxRequestSize=100MB //多个文件最大限制

4、自动配置原理

文件上传自动配置类-MultipartAutoConfiguration-MultipartProperties

  • 自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
  • 原理步骤
    • 1、请求进来使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回MultipartHttpServletRequest)文件上传请求
    • 2、参数解析器来解析请求中的文件内容封装成MultipartFile
    • 3、将request中文件信息封装为一个Map;MultiValueMap

FileCopyUtils。实现文件流的拷贝

  1. @PostMapping("/upload")
  2. public String upload(@RequestParam("email") String email,
  3. @RequestParam("username") String username,
  4. @RequestPart("headerImg") MultipartFile headerImg,
  5. @RequestPart("photos") MultipartFile[] photos)

SpringBoot2 - 图25

8、异常处理

错误处理

1、默认规则

  • 默认情况下,Spring Boot提供/error处理所有错误的映射
  • 对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
  • SpringBoot2 - 图26SpringBoot2 - 图27
  • 要对其进行自定义,添加**View**解析为**error**``** **
  • 要完全替换默认行为,可以实现 ErrorController并注册该类型的Bean定义,或添加ErrorAttributes类型的组件以使用现有机制但替换其内容。
  • error/下的4xx,5xx页面会被自动解析;
    • SpringBoot2 - 图28

2、定制错误处理逻辑

  • 自定义错误页
    • error/404.html error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html;如果都没有就触发白页
  • @ControllerAdvice+@ExceptionHandler处理全局异常;底层是 ExceptionHandlerExceptionResolver 支持的
  • @ResponseStatus+自定义异常 ;底层是 ResponseStatusExceptionResolver ,把responsestatus注解的信息底层调用 response.sendError(statusCode, resolvedReason);tomcat发送的/error
  • Spring底层的异常,如 参数类型转换异常;DefaultHandlerExceptionResolver 处理框架底层的异常。
    • response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    • SpringBoot2 - 图29
  • 自定义实现 HandlerExceptionResolver 处理异常;可以作为默认的全局异常处理规则
    • SpringBoot2 - 图30
  • ErrorViewResolver 实现自定义处理异常;
    • response.sendError 。error请求就会转给controller
    • 你的异常没有任何人能处理。tomcat底层 response.sendError。error请求就会转给controller
    • basicErrorController 要去的页面地址是 ErrorViewResolver

3、异常处理自动配置原理

  • ErrorMvcAutoConfiguration 自动配置异常处理规则
    • 容器中的组件:类型:DefaultErrorAttributes -> id:errorAttributes
      • public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver
      • DefaultErrorAttributes:定义错误页面中可以包含哪些数据。
      • SpringBoot2 - 图31
      • SpringBoot2 - 图32
    • 容器中的组件:类型:BasicErrorController —> id:basicErrorController(json+白页 适配响应)
      • 处理默认 /error 路径的请求;页面响应 new ModelAndView(“error”, model);
      • 容器中有组件 View->id是error;(响应默认错误页)
      • 容器中放组件 BeanNameViewResolver(视图解析器);按照返回的视图名作为组件的id去容器中找View对象。
    • 容器中的组件:类型:DefaultErrorViewResolver -> id:conventionErrorViewResolver
      • 如果发生错误,会以HTTP的状态码 作为视图页地址(viewName),找到真正的页面
      • error/404、5xx.html

如果想要返回页面;就会找error视图【StaticView】。(默认是一个白页)

SpringBoot2 - 图33写出去json

SpringBoot2 - 图34 错误页

4、异常处理步骤流程

1、执行目标方法,目标方法运行期间有任何异常都会被catch、而且标志当前请求结束;并且用 dispatchException

2、进入视图解析流程(页面渲染?)

processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);

3、mv = processHandlerException;处理handler发生的异常,处理完成返回ModelAndView;

  • 1、遍历所有的 handlerExceptionResolvers,看谁能处理当前异常【HandlerExceptionResolver处理器异常解析器】
  • SpringBoot2 - 图35
  • 2、系统默认的 异常解析器;
  • SpringBoot2 - 图36
    • 1、DefaultErrorAttributes先来处理异常。把异常信息保存到rrequest域,并且返回null;
    • 2、默认没有任何人能处理异常,所以异常会被抛出
      • 1、如果没有任何人能处理最终底层就会发送 /error 请求。会被底层的BasicErrorController处理
      • 2、解析错误视图;遍历所有的 ErrorViewResolver 看谁能解析。
      • SpringBoot2 - 图37
      • 3、默认的 DefaultErrorViewResolver ,作用是把响应状态码作为错误页的地址,error/500.html
      • 4、模板引擎最终响应这个页面 error/500.html

9、Web原生组件注入(Servlet、Filter、Listener)

1、使用Servlet API

  • @ServletComponentScan(basePackages = “com.atguigu.admin”) :指定原生Servlet组件都放在那里

    1. @ServletComponentScan(basePackages = "com.example.pratice_springboot")
    2. @SpringBootApplication
    3. public class PraticeSpringbootApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(PraticeSpringbootApplication.class, args);
    6. }
    7. }
  • @WebServlet(urlPatterns = “/my”):效果:直接响应,没有经过Spring的拦截器?

    1. @WebServlet(urlPatterns = "/myserlvet")
    2. public class MyServlet extends HttpServlet {
    3. @Override
    4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    5. resp.getWriter().write("666666");
    6. }
    7. }
  • @WebFilter(urlPatterns={“/css/*”,“/images/*”})

    1. @Slf4j
    2. //原生servlet使用/*,springboot使用/**
    3. @WebFilter(urlPatterns = "/css/*,/images/*")
    4. public class MyFilter implements Filter {
    5. @Override
    6. public void init(FilterConfig filterConfig) throws ServletException {
    7. log.info("MyFilter初始化完成!!!");
    8. }
    9. @Override
    10. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    11. log.info("MyFilter正在执行!!!");
    12. filterChain.doFilter(servletRequest, servletResponse);
    13. }
    14. @Override
    15. public void destroy() {
    16. log.info("MyFilter被销毁!!!");
    17. }
    18. }
  • @WebListener

    1. @Slf4j
    2. @WebListener()
    3. public class MyListener implements ServletContextListener {
    4. @Override
    5. public void contextInitialized(ServletContextEvent sce) {
    6. log.info("MyListener监听到项目创建");
    7. }
    8. @Override
    9. public void contextDestroyed(ServletContextEvent sce) {
    10. log.info("MyListener监听到项目销毁");
    11. }
    12. }

推荐可以这种方式;

扩展:DispatchServlet 如何注册进来

  1. @Bean(
  2. name = {"dispatcherServletRegistration"}
  3. )
  4. @ConditionalOnBean(
  5. value = {DispatcherServlet.class},
  6. name = {"dispatcherServlet"}
  7. )
  8. public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) {
  9. DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, webMvcProperties.getServlet().getPath());
  10. registration.setName("dispatcherServlet");
  11. registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());
  12. multipartConfig.ifAvailable(registration::setMultipartConfig);
  13. return registration;
  14. }
  15. }
  • 容器中自动配置了 DispatcherServlet 属性绑定到 WebMvcProperties;对应的配置文件配置项是 spring.mvc。
  • 通过 ServletRegistrationBean 把 DispatcherServlet 配置进来。
  • 默认映射的是 / 路径。
    1. private String path = "/";

SpringBoot2 - 图38

Tomcat-Servlet;

多个Servlet都能处理到同一层路径,精确优选原则

A: /my/

B: /my/1

2、使用RegistrationBean(代替注解)

  1. ServletRegistrationBean`, `FilterRegistrationBean`, and `ServletListenerRegistrationBean
  2. @Configuration
  3. public class MyRegistConfig {
  4. //将servlet注入到组件中
  5. @Bean
  6. public ServletRegistrationBean myServlet(){
  7. MyServlet myServlet = new MyServlet();
  8. return new ServletRegistrationBean(myServlet,"/my","/my02");
  9. }
  10. @Bean
  11. public FilterRegistrationBean myFilter(){
  12. MyFilter myFilter = new MyFilter();
  13. //使用servlet的路径
  14. // return new FilterRegistrationBean(myFilter,myServlet());
  15. //自定义路径
  16. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
  17. filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
  18. return filterRegistrationBean;
  19. }
  20. @Bean
  21. public ServletListenerRegistrationBean myListener(){
  22. MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
  23. return new ServletListenerRegistrationBean(mySwervletContextListener);
  24. }
  25. }

10、嵌入式Servlet容器

1、切换嵌入式Servlet容器

  • 默认支持的webServer
    • Tomcat, Jetty, or Undertow
    • ServletWebServerApplicationContext 容器启动寻找ServletWebServerFactory 并引导创建服务器
  • 切换服务器

SpringBoot2 - 图39

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-tomcat</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  • 原理
    • SpringBoot应用启动发现当前是Web应用。web场景包-导入tomcat
    • web应用会创建一个web版的ioc容器 ServletWebServerApplicationContext
    • ServletWebServerApplicationContext 启动的时候寻找 **ServletWebServerFactory**``(Servlet 的web服务器工厂---> Servlet 的web服务器)
    • SpringBoot底层默认有很多的WebServer工厂;TomcatServletWebServerFactory, JettyServletWebServerFactory, or UndertowServletWebServerFactory
    • 底层直接会有一个自动配置类。ServletWebServerFactoryAutoConfiguration
    • ServletWebServerFactoryAutoConfiguration导入了ServletWebServerFactoryConfiguration(配置类)
    • ServletWebServerFactoryConfiguration 配置类 根据动态判断系统中到底导入了那个Web服务器的包。(默认是web-starter导入tomcat包),容器中就有 TomcatServletWebServerFactory
    • TomcatServletWebServerFactory 创建出Tomcat服务器并启动;TomcatWebServer 的构造器拥有初始化方法initialize---this.tomcat.start();
    • 内嵌服务器,就是手动把启动服务器的代码调用(tomcat核心jar包存在)
  • ``

2、定制Servlet容器

  • 实现 WebServerFactoryCustomizer
    • 把配置文件的值和**ServletWebServerFactory 进行绑定**
  • 修改配置文件 server.xxx
  • 直接自定义 ConfigurableServletWebServerFactory

xxxxxCustomizer:定制化器,可以改变xxxx的默认规则

  1. import org.springframework.boot.web.server.WebServerFactoryCustomizer;
  2. import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
  6. @Override
  7. public void customize(ConfigurableServletWebServerFactory server) {
  8. server.setPort(9000);
  9. }
  10. }

11、定制化原理

1、定制化的常见方式

  • 修改配置文件;
  • xxxxxCustomizer;
  • 编写自定义的配置类 xxxConfiguration;+ @Bean替换、增加容器中默认组件;视图解析器
  • Web应用 编写一个配置类实现 WebMvcConfigurer 即可定制化web功能;+ @Bean给容器中再扩展一些组件
  1. @Configuration
  2. public class AdminWebConfig implements WebMvcConfigurer
  • @EnableWebMvc + WebMvcConfigurer —— @Bean 可以全面接管SpringMVC,所有规则全部自己重新配置; 实现定制和扩展功能
    • 原理
    • 1、WebMvcAutoConfiguration 默认的SpringMVC的自动配置功能类。静态资源、欢迎页…..
    • 2、一旦使用 @EnableWebMvc 、。会 @Import(DelegatingWebMvcConfiguration. class)
    • 3、DelegatingWebMvcConfiguration 的 作用,只保证SpringMVC最基本的使用
      • 把所有系统中的 WebMvcConfigurer 拿过来。所有功能的定制都是这些 WebMvcConfigurer 合起来一起生效
      • 自动配置了一些非常底层的组件。RequestMappingHandlerMapping、这些组件依赖的组件都是从容器中获取
      • public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
    • 4、WebMvcAutoConfiguration 里面的配置要能生效 必须 @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    • 5、@EnableWebMvc 导致了 WebMvcAutoConfiguration 没有生效。

2、原理分析套路

场景starter - xxxxAutoConfiguration - 导入xxx组件 - 绑定xxxProperties — 绑定配置文件项

数据访问

1、SQL

1、数据源的自动配置-HikariDataSource

1、导入JDBC场景

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jdbc</artifactId>
  4. </dependency>

SpringBoot2 - 图40

数据库驱动?

为什么导入JDBC场景,官方不导入驱动?官方不知道我们接下要操作什么数据库。

数据库版本和驱动版本对应

  1. 默认版本:<mysql.version>8.0.22</mysql.version>
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <!-- <version>5.1.49</version>-->
  6. </dependency>
  7. 想要修改版本
  8. 1、直接依赖引入具体版本(maven的就近依赖原则)
  9. 2、重新声明版本(maven的属性的就近优先原则)
  10. <properties>
  11. <java.version>1.8</java.version>
  12. <mysql.version>5.1.49</mysql.version>
  13. </properties>

2、分析自动配置

1、自动配置的类

  • DataSourceAutoConfiguration : 数据源的自动配置
    • 修改数据源相关的配置:spring.datasource
    • 数据库连接池的配置,是自己容器中没有DataSource才自动配置的
    • 底层配置好的连接池是:HikariDataSource
  1. @Configuration(proxyBeanMethods = false)
  2. @Conditional(PooledDataSourceCondition.class)
  3. @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
  4. @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
  5. DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
  6. DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
  7. protected static class PooledDataSourceConfiguration
  • DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置
  • JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud
  • JndiDataSourceAutoConfiguration: jndi的自动配置
  • XADataSourceAutoConfiguration: 分布式事务相关的

3、修改配置项

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/user
  4. username: root
  5. password: LJLljl20020728.+
  6. driver-class-name: com.mysql.cj.jdbc.Driver

4、测试

  1. @Slf4j
  2. @SpringBootTest
  3. class Boot05WebAdminApplicationTests {
  4. @Autowired
  5. JdbcTemplate jdbcTemplate;
  6. @Test
  7. void contextLoads() {
  8. // jdbcTemplate.queryForObject("select * from account_tbl")
  9. // jdbcTemplate.queryForList("select * from account_tbl",)
  10. Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tbl", Long.class);
  11. log.info("记录总数:{}",aLong);
  12. }
  13. }

2、使用Druid数据源

1、druid官方github地址

https://github.com/alibaba/druid

整合第三方技术的两种方式

  • 自定义
  • 找starter

2、自定义方式

1、创建数据源

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid</artifactId>
  4. <version>1.1.17</version>
  5. </dependency>
  6. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  7. destroy-method="close">
  8. <property name="url" value="${jdbc.url}" />
  9. <property name="username" value="${jdbc.username}" />
  10. <property name="password" value="${jdbc.password}" />
  11. <property name="maxActive" value="20" />
  12. <property name="initialSize" value="1" />
  13. <property name="maxWait" value="60000" />
  14. <property name="minIdle" value="1" />
  15. <property name="timeBetweenEvictionRunsMillis" value="60000" />
  16. <property name="minEvictableIdleTimeMillis" value="300000" />
  17. <property name="testWhileIdle" value="true" />
  18. <property name="testOnBorrow" value="false" />
  19. <property name="testOnReturn" value="false" />
  20. <property name="poolPreparedStatements" value="true" />
  21. <property name="maxOpenPreparedStatements" value="20" />

2、StatViewServlet

StatViewServlet的用途包括:

  • 提供监控信息展示的html页面
  • 提供监控信息的JSON API
  1. <servlet>
  2. <servlet-name>DruidStatView</servlet-name>
  3. <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>DruidStatView</servlet-name>
  7. <url-pattern>/druid/*</url-pattern>
  8. </servlet-mapping>

3、StatFilter

用于统计监控信息;如SQL监控、URI监控

  1. 需要给数据源中配置如下属性;可以允许多个filter,多个用,分割;如:
  2. <property name="filters" value="stat,slf4j" />

系统中所有filter:

别名 Filter类名
default com.alibaba.druid.filter.stat.StatFilter
stat com.alibaba.druid.filter.stat.StatFilter
mergeStat com.alibaba.druid.filter.stat.MergeStatFilter
encoding com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j com.alibaba.druid.filter.logging.Log4jFilter
log4j2 com.alibaba.druid.filter.logging.Log4j2Filter
slf4j com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging com.alibaba.druid.filter.logging.CommonsLogFilter

慢SQL记录配置

  1. <bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
  2. <property name="slowSqlMillis" value="10000" />
  3. <property name="logSlowSql" value="true" />
  4. </bean>
  5. 使用 slowSqlMillis 定义慢SQL的时长

3、使用官方starter方式

1、引入druid-starter

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid-spring-boot-starter</artifactId>
  4. <version>1.1.17</version>
  5. </dependency>

2、分析自动配置

  1. @Configuration
  2. @ConditionalOnClass({DruidDataSource.class})
  3. @AutoConfigureBefore({DataSourceAutoConfiguration.class})
  4. @EnableConfigurationProperties({DruidStatProperties.class, DataSourceProperties.class})
  5. @Import({DruidSpringAopConfiguration.class, DruidStatViewServletConfiguration.class, DruidWebStatFilterConfiguration.class, DruidFilterConfiguration.class})
  6. public class DruidDataSourceAutoConfigure {
  • 扩展配置项 spring.datasource.druid
  • DruidSpringAopConfiguration.class, 监控SpringBean的;配置项:spring.datasource.druid.aop-patterns
  • DruidStatViewServletConfiguration.class, 监控页的配置:spring.datasource.druid.stat-view-servlet;默认开启
  • DruidWebStatFilterConfiguration.class, web监控配置;spring.datasource.druid.web-stat-filter;默认开启
  • DruidFilterConfiguration.class}) 所有Druid自己filter的配置
  1. private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat";
  2. private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config";
  3. private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding";
  4. private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j";
  5. private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j";
  6. private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2";
  7. private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log";
  8. private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";

3、配置示例

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/user
  4. username: root
  5. password: LJLljl20020728.+
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. druid:
  8. aop-patterns: com.example.pratice_springboot.*
  9. filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙)
  10. stat-view-servlet: # 配置监控页功能
  11. enabled: true
  12. login-username: admin
  13. login-password: admin
  14. resetEnable: false #关闭重置按钮
  15. web-stat-filter: # 监控web
  16. enabled: true
  17. urlPattern: /*
  18. exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
  19. filter:
  20. stat: # 对上面filters里面的stat的详细配置
  21. slow-sql-millis: 1000
  22. logSlowSql: true
  23. enabled: true
  24. wall:
  25. enabled: true
  26. config:
  27. drop-table-allow: false

在路径http://localhost:8080/druid下可以查看druid的监控页面等

SpringBoot配置示例

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

配置项列表https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8

3、整合MyBatis操作

https://github.com/mybatis

starter

SpringBoot官方的Starter:spring-boot-starter-*

第三方的: *-spring-boot-starter

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>2.1.4</version>
  5. </dependency>

SpringBoot2 - 图41

1、配置模式

  • 全局配置文件
  • SqlSessionFactory: 自动配置好了
  • SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
  • @Import(AutoConfiguredMapperScannerRegistrar.class);
  • Mapper: 只要我们写的操作MyBatis的接口标准了 @Mapper 就会被自动扫描进来
  1. @EnableConfigurationProperties(MybatisProperties.class) MyBatis配置项绑定类。
  2. @AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
  3. public class MybatisAutoConfiguration{}
  4. @ConfigurationProperties(prefix = "mybatis")
  5. public class MybatisProperties

可以修改配置文件中 mybatis 开始的所有;

  1. # 配置mybatis规则
  2. mybatis:
  3. config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置
  4. mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
  5. Mapper接口--->绑定Xml
  6. <?xml version="1.0" encoding="UTF-8" ?>
  7. <!DOCTYPE mapper
  8. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  9. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  10. <mapper namespace="com.example.pratice_springboot.mapper.AccountMapper">
  11. <select id="getAccountById" resultType="com.example.pratice_springboot.bean.Account">
  12. select * from account where user_id=#{userId}
  13. </select>
  14. </mapper>

配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值

  1. # 配置mybatis规则
  2. mybatis:
  3. # config-location: classpath:mybatis/mybatis-config.xml
  4. mapper-locations: classpath:mybatis/mapper/*.xml
  5. configuration:
  6. map-underscore-to-camel-case: true #开启驼峰命名规则
  7. 可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
  • 导入mybatis官方starter
  • 编写mapper接口。标准@Mapper注解
  • 编写sql映射文件并绑定mapper接口
  • 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration

2、注解模式

  1. @Mapper
  2. public interface CityMapper {
  3. @Select("select * from city where id=#{id}")
  4. public City getById(Long id);
  5. public void insert(City city);
  6. }

3、混合模式

  1. @Mapper
  2. public interface CityMapper {
  3. @Select("select * from city where id=#{id}")
  4. public City getById(Long id);
  5. public void insert(City city);
  6. }

最佳实战:

  • 引入mybatis-starter
  • 配置application.yaml中,指定mapper-location位置即可
  • 编写Mapper接口并标注@Mapper注解
  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射
  • @MapperScan(“com.atguigu.admin.mapper”) 简化,其他的接口就可以不用标注@Mapper注解

单元测试

1、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的测试引擎。

SpringBoot2 - 图42

注意:

SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test

JUnit 5’s Vintage Engine Removed from **spring-boot-starter-test,如果需要继续兼容junit4需要自行引入vintage**

  1. <dependency>
  2. <groupId>org.junit.vintage</groupId>
  3. <artifactId>junit-vintage-engine</artifactId>
  4. <scope>test</scope>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>org.hamcrest</groupId>
  8. <artifactId>hamcrest-core</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>

SpringBoot2 - 图43

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-test</artifactId>
  4. <scope>test</scope>
  5. </dependency>

现在版本:

  1. @SpringBootTest
  2. class Boot05WebAdminApplicationTests {
  3. @Test
  4. void contextLoads() {
  5. }
  6. }

以前:

@SpringBootTest + @RunWith(SpringTest.class)

SpringBoot整合Junit以后。

  • 编写测试方法:@Test标注(注意需要使用junit5版本的注解)
  • Junit类具有Spring的功能,@Autowired、比如 @Transactional 标注测试方法,测试完成后自动回滚

2、JUnit5常用注解

JUnit5的注解与JUnit4的注解有所变化

https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

  • @Test : 表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
  • @ParameterizedTest : 表示方法是参数化测试,下方会有详细介绍
  • @RepeatedTest : 表示方法可重复执行,下方会有详细介绍
  • @DisplayName : 为测试类或者测试方法设置展示名称
  • @BeforeEach : 表示在每个单元测试之前执行
  • @AfterEach : 表示在每个单元测试之后执行
  • @BeforeAll : 表示在所有单元测试之前执行
  • @AfterAll : 表示在所有单元测试之后执行
  • @Tag : 表示单元测试类别,类似于JUnit4中的@Categories
  • @Disabled : 表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
  • @Timeout : 表示测试方法运行如果超过了指定时间将会返回错误
  • @ExtendWith : 为测试类或测试方法提供扩展类引用
  1. import org.junit.jupiter.api.Test; //注意这里使用的是jupiter的Test注解!!
  2. public class TestDemo {
  3. @Test
  4. @DisplayName("第一次测试")
  5. public void firstTest() {
  6. System.out.println("hello world");
  7. }

3、断言(assertions)

断言(assertions)是测试方法中的核心部分,用来对测试需要满足的条件进行验证。这些断言方法都是 org.junit.jupiter.api.Assertions 的静态方法。JUnit 5 内置的断言可以分成如下几个类别:

检查业务逻辑返回的数据是否合理。

所有的测试运行结束以后,会有一个详细的测试报告;

1、简单断言

用来对单个值进行简单的验证。如:

方法 说明
assertEquals 判断两个对象或两个原始类型是否相等
assertNotEquals 判断两个对象或两个原始类型是否不相等
assertSame 判断两个对象引用是否指向同一个对象
assertNotSame 判断两个对象引用是否指向不同的对象
assertTrue 判断给定的布尔值是否为 true
assertFalse 判断给定的布尔值是否为 false
assertNull 判断给定的对象引用是否为 null
assertNotNull 判断给定的对象引用是否不为 null
  1. @Test
  2. @DisplayName("simple assertion")
  3. public void simple() {
  4. assertEquals(3, 1 + 2, "simple math");
  5. assertNotEquals(3, 1 + 1);
  6. assertNotSame(new Object(), new Object());
  7. Object obj = new Object();
  8. assertSame(obj, obj);
  9. assertFalse(1 > 2);
  10. assertTrue(1 < 2);
  11. assertNull(null);
  12. assertNotNull(new Object());
  13. }

2、数组断言

通过 assertArrayEquals 方法来判断两个对象或原始类型的数组是否相等

  1. @Test
  2. @DisplayName("array assertion")
  3. public void array() {
  4. assertArrayEquals(new int[]{1, 2}, new int[] {1, 2});
  5. }

3、组合断言

assertAll 方法接受多个 org.junit.jupiter.api.Executable 函数式接口的实例作为要验证的断言,可以通过 lambda 表达式很容易的提供这些断言

  1. @Test
  2. @DisplayName("assert all")
  3. public void all() {
  4. assertAll("Math",
  5. () -> assertEquals(2, 1 + 1),
  6. () -> assertTrue(1 > 0)
  7. );
  8. }

4、异常断言

在JUnit4时期,想要测试方法的异常情况时,需要用@Rule 注解的ExpectedException变量还是比较麻烦的。而JUnit5提供了一种新的断言方式Assertions.assertThrows() ,配合函数式编程就可以进行使用。

  1. @Test
  2. @DisplayName("异常测试")
  3. public void exceptionTest() {
  4. ArithmeticException exception = Assertions.assertThrows(
  5. //扔出断言异常
  6. ArithmeticException.class, () -> System.out.println(1 % 0));
  7. }

5、超时断言

Junit5还提供了Assertions.assertTimeout() 为测试方法设置了超时时间

  1. @Test
  2. @DisplayName("超时测试")
  3. public void timeoutTest() {
  4. //如果测试方法时间超过1s将会异常
  5. Assertions.assertTimeout(Duration.ofMillis(1000), () -> Thread.sleep(500));
  6. }

6、快速失败

通过 fail 方法直接使得测试失败

  1. @Test
  2. @DisplayName("fail")
  3. public void shouldFail() {
  4. fail("This should fail");
  5. }

4、前置条件(assumptions)

JUnit 5 中的前置条件(assumptions【假设】)类似于断言,不同之处在于不满足的断言会使得测试方法失败,而不满足的前置条件只会使得测试方法的执行终止。前置条件可以看成是测试方法执行的前提,当该前提不满足时,就没有继续执行的必要。

  1. @DisplayName("前置条件")
  2. public class AssumptionsTest {
  3. private final String environment = "DEV";
  4. @Test
  5. @DisplayName("simple")
  6. public void simpleAssume() {
  7. assumeTrue(Objects.equals(this.environment, "DEV"));
  8. assumeFalse(() -> Objects.equals(this.environment, "PROD"));
  9. }
  10. @Test
  11. @DisplayName("assume then do")
  12. public void assumeThenDo() {
  13. assumingThat(
  14. Objects.equals(this.environment, "DEV"),
  15. () -> System.out.println("In DEV")
  16. );
  17. }
  18. }

assumeTrue 和 assumFalse 确保给定的条件为 true 或 false,不满足条件会使得测试执行终止。assumingThat 的参数是表示条件的布尔值和对应的 Executable 接口的实现对象。只有条件满足时,Executable 对象才会被执行;当条件不满足时,测试执行并不会终止。

5、嵌套测试

JUnit 5 可以通过 Java 中的内部类和@Nested 注解实现嵌套测试,从而可以更好的把相关的测试方法组织在一起。在内部类中可以使用@BeforeEach @AfterEach 注解,而且嵌套的层次没有限制。

内层的Test可以驱动外层的Before(After)Each/All之类的方法前提/之后运行,而内层可以驱动外层

  1. @DisplayName("A stack")
  2. class TestingAStackDemo {
  3. Stack<Object> stack;
  4. @Test
  5. @DisplayName("is instantiated with new Stack()")
  6. void isInstantiatedWithNew() {
  7. new Stack<>();
  8. }
  9. @Nested
  10. @DisplayName("when new")
  11. class WhenNew {
  12. @BeforeEach
  13. void createNewStack() {
  14. stack = new Stack<>();
  15. }
  16. @Test
  17. @DisplayName("is empty")
  18. void isEmpty() {
  19. assertTrue(stack.isEmpty());
  20. }
  21. @Test
  22. @DisplayName("throws EmptyStackException when popped")
  23. void throwsExceptionWhenPopped() {
  24. assertThrows(EmptyStackException.class, stack::pop);
  25. }
  26. @Test
  27. @DisplayName("throws EmptyStackException when peeked")
  28. void throwsExceptionWhenPeeked() {
  29. assertThrows(EmptyStackException.class, stack::peek);
  30. }
  31. @Nested
  32. @DisplayName("after pushing an element")
  33. class AfterPushing {
  34. String anElement = "an element";
  35. @BeforeEach
  36. void pushAnElement() {
  37. stack.push(anElement);
  38. }
  39. @Test
  40. @DisplayName("it is no longer empty")
  41. void isNotEmpty() {
  42. assertFalse(stack.isEmpty());
  43. }
  44. @Test
  45. @DisplayName("returns the element when popped and is empty")
  46. void returnElementWhenPopped() {
  47. assertEquals(anElement, stack.pop());
  48. assertTrue(stack.isEmpty());
  49. }
  50. @Test
  51. @DisplayName("returns the element when peeked but remains not empty")
  52. void returnElementWhenPeeked() {
  53. assertEquals(anElement, stack.peek());
  54. assertFalse(stack.isEmpty());
  55. }
  56. }
  57. }
  58. }

6、参数化测试

参数化测试是JUnit5很重要的一个新特性,它使得用不同的参数多次运行测试成为了可能,也为我们的单元测试带来许多便利。

利用@ValueSource 等注解,指定入参,我们将可以使用不同的参数进行多次单元测试,而不需要每新增一个参数就新增一个单元测试,省去了很多冗余代码。

@ValueSource : 为参数化测试指定入参来源,支持八大基础类以及String类型,Class类型

@NullSource : 表示为参数化测试提供一个null的入参

@EnumSource : 表示为参数化测试提供一个枚举入参

@CsvFileSource :表示读取指定CSV文件内容作为参数化测试入参

@MethodSource :表示读取指定方法的返回值作为参数化测试入参(注意方法返回需要是一个流)

当然如果参数化测试仅仅只能做到指定普通的入参还达不到让我觉得惊艳的地步。让我真正感到他的强大之处的地方在于他可以支持外部的各类入参。如:CSV,YML,JSON 文件甚至方法的返回值也可以作为入参。只需要去实现ArgumentsProvider接口,任何外部文件都可以作为它的入参。

  1. @ParameterizedTest
  2. @ValueSource(strings = {"one", "two", "three"})
  3. @DisplayName("参数化测试1")
  4. public void parameterizedTest1(String string) {
  5. System.out.println(string);
  6. Assertions.assertTrue(StringUtils.isNotBlank(string));
  7. }
  8. @ParameterizedTest
  9. @MethodSource("method") //指定方法名
  10. @DisplayName("方法来源参数")
  11. public void testWithExplicitLocalMethodSource(String name) {
  12. System.out.println(name);
  13. Assertions.assertNotNull(name);
  14. }
  15. static Stream<String> method() {
  16. return Stream.of("apple", "banana");
  17. }

7、迁移指南

在进行迁移的时候需要注意如下的变化: