经典再现,看到就是赚到。尚硅谷雷神 - SpringBoot 2.0学习笔记 - 基础入门篇

SpringBoot 2.0

视频学习地址:https://www.bilibili.com/video/BV1Et411Y7tQ?p=112&spm_id_from=pageDriver

1、Spring与SpringBoot

1.1、Spring是什么?Spring能做什么?

Spring 被称为 J2EE 的春天,是一个开源的轻量级的 Java 开发框架, 具有控制反转(IOC)面向切面(AOP)两大核心。Java Spring 框架通过声明式方式灵活地进行事务的管理,提高开发效率和质量。

Spring 框架不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何 Java 应用都可以从 Spring 中受益。Spring 框架还是一个超级粘合平台,除了自己提供功能外,还提供粘合其他技术和框架的能力。

那么Spring能做什么呢?在Spring官网介绍得知:
在这里插入图片描述

1.2、Spring 5 的重大升级

Spring 5于2017年9月发布了通用版本,它是自2013年12月以来第一 个主要的Spring版本。它提供了一些人们期待已久的改进,还采用了一种全新的编程范例,以反应式原则为基础。

这个版本是很长时间以来最令人激动的版本。Spring 5兼容JavaTM8 和JDK 9,它集成了反应式流,以方便后续提供一种颠覆性方法来实现端点和Web应用程序开发。

spring5带来的特性和改变,主要包含以下关键内容:

  1. JDK 基线和库更新、支持
  2. 使用JDK8和JDK9新特性
  3. 反应式编程模型
  4. 含 Kotlin 在内的函数式编程
  5. 测试改进和提升
  6. spring核心迭代和一般性修订
  7. 中止支持等等

这也导致了SpringBoot2.0在内部设计上比较1.0版本发生了很多改变,所以了解一些Spring5的新特性,对于我们学习Spring2.0有很大的帮助。

1.2.1、响应式编程

Spring 5 Framework 基于一种反应式基础而构建,而且是完全异步和非阻塞的。只需少量的线程,新的事件循环执行模型就可以垂直扩展。

该框架采用反应式流来提供在反应式组件中传播负压的机制。负压是一个确保来自多个生产者的数据不会让使用者不堪重负的概念。

Spring WebFlux 是 Spring 5 的反应式核心,它为开发人员提供了两种为 Spring Web 编程而设计的编程模型:一种基于注解的模型和 Functional Web Framework (WebFlux.fn)。

基于注解的模型是 Spring WebMVC 的现代替代方案,该模型基于反应式基础而构建,而 Functional Web Framework 是基于 @Controller 注解的编程模型的替代方案。这些模型都通过同一种反应式基础来运行,后者调整非阻塞 HTTP 来适应反应式流 API。

所以SpringBoot2.0可以使用两种技术栈实现应用的开发:

  • 传统模式开发(Servlet Stack)
  • 响应式开发(Reactive Stack)。少量线程占有少量资源,更具优势。

在这里插入图片描述

1.2.2、内部源码设计

Spring5 的基准版本为8,因此它使用了 Java8 和9的许多新特性。例如:

  1. Spring 接口中的默认方法(JDK9)。

  2. 基于 Java8 反射增强的内部代码改进(JDK8)。

  3. 在框架代码中使用函数式编程 - lambda表达式 和 stream流(JDK8)。

  4. 支持HTTP/2(JDK9)。以下将针对JDK版本内容解释说明。

1、HTTP/2方面的支持

HTTP/2提高了传输性能,减少了延迟并提高了应用程序的吞吐量从而提供了丰富的Web体验。Spring 5提供专门的HTTP/2特性支持(由Tomcat 9.0、Jetty 9.3 和Undertow 1.4提供)。

2、Lambda表达式注册Bean实例

传统注册bean使用XML配置或者javaConfig进行实例,但是这些在5.0后也有新方案,我们可以使用Lambda表达式进行bean的实例处理:

context.registerBean(TestBean.class, () -> newTestBean(context.getBean(Test.class)));

所以在SpringBoot2.0中利用 Java 8 和 Java9 的新特性,大量重构了源码。

1.3、为什么要用SpringBoot ?

在Spring的官网里有这样一句话:
在这里插入图片描述
翻译过来就是:

SpringBoot使得创建独立的、生产级的基于Spring的应用程序变得很容易,并且您可以快速运行这些应用程序。

1.3.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技术栈的快速开发脚手架。

1.3.2、SpringBoot的缺点

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

1.4、SpringBoot所处的时代背景

1.4.1、微服务

James Lewis and Martin Fowler (2014) 提出微服务完整概念。论文期刊地址:https://martinfowler.com/articles/microservices.html

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交互
  • 服务围绕业务功能拆分
  • 可以由全自动部署机制独立部署
  • 去中心化,服务自治。服务可以使用不同的语言、不同的存储技术

1.4.2、分布式

在这里插入图片描述
分布式的困难

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

分布式问题的解决:

SpringBoot + SpringCloud
在这里插入图片描述

1.4.3、云原生

原生应用如何上云。 Cloud Native

上云的困难

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

上云问题的解决

  • Docker容器化技术
  • 容器编排Kubernetes
  • DevOps
  • Service Mesh与Serverless等等

1.5、如何学习SpringBoot ?

熟悉SpringBoot官网是最好的学习方式!官网地址:https://spring.io/projects/spring-boot

2、SpringBoot 2 入门

2.1、环境要求

  • Java 8 & 兼容 Java 14
  • Maven 3.3 +

修改 maven 全局配置文件(E:\maven\apache-maven-3.6.3\conf\settings.xml)

<!-- 指定本机仓库地址 -->
<localRepository>E:/maven/repository</localRepository>

<mirrors>
    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>        
    </mirror>
  </mirrors>
 <!-- 使用jdk 1.8 编译项目 -->
  <profiles>
     <profile>
        <id>jdk1.8</id>
        <activation>
            <activeByDefault>true</activeByDefault>
            <jdk>1.8</jdk>
        </activation>
        <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        </properties>
    </profile>
  </profiles>

2.2、SpringBoot的第一个入门程序

2.2.1、实现步骤

1、创建一个maven工程(创建一个pom.xml文件)
在这里插入图片描述
2、引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.laizhenghua</groupId>
    <artifactId>boot-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
    </parent>
    <dependencies>
        <!-- web 场景启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

3、创建主程序

/**
 * @description: 主程序类
 * @author: laizhenghua
 * @date: 2021/3/23 21:39
 */
@SpringBootApplication // 标注SpringBoot应用
public class MainApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(MainApplication.class,args);
    }
}

4、编写业务

/**
 * @description: 控制层
 * @author: laizhenghua
 * @date: 2021/3/23 21:44
 */
@Controller
public class HelloController {
    
    

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    @ResponseBody
    public String hello() {
    
    
        return "hello world";
    }
}

5、启动主程序并测试

访问:http://localhost:8080/hello

2.2.2、简化配置初体验

resources目录下新建一个文件application.yml,这里使用yaml文件,也是官方推荐使用的,更多yaml的知识后面会涉及到。

server:
  port: 8888 # 指定端口号
  servlet:
    context-path: /hello # 指定根路径

启动日志:Tomcat started on port(s): 8888 (http) with context path '/hello'

那么application properties/yaml 都可以配置那些内容呢?官方文档有详细介绍

https://docs.spring.io/spring-boot/docs/2.3.9.RELEASE/reference/html/appendix-application-properties.html#common-application-properties

2.2.3、简化部署

SpringBoot可以编译成可执行的 jar 包来简化部署。

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

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

java -jar boot-helloworld-1.0-SNAPSHOT.jar

3、自动配置初体验

3.1、依赖管理

1、父项目做依赖管理

我们知道每个SpringBoot项目的pom.xml都有父项目依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.9.RELEASE</version>
</parent>
<!-- 几乎声明了所有开发中常用的依赖的版本号,无需关注版本号,自动版本仲裁机制(引入非版本仲裁的jar,要写版本号) -->

子项目都继承了父项目的依赖,言外之意就是父项目管理了大多数我们需要的依赖,当我们需要其他依赖时,只需要在子项目中引入即可。

当我们需要指定依赖版本号时,只需根据spring-boot-dependencies-2.x.x.RELEASE.pom的版本号标签名,在子项目中创建<properties>标签用于指定依赖版本号 – 就近优先原则。

例如:我们想要在子项目中引入MySQL 5.1.43 的依赖

1、查看spring-boot-dependencies里面规定当前依赖的版本的标签名。
在这里插入图片描述
2、在当前项目里面重写配置

 <properties>
     <mysql.version>5.1.43</mysql.version>
 </properties>
 
 <!-- 注意以下坐标要在dependencies标签内 -->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
 </dependency>

在这里插入图片描述
2、开发导入starter场景启动器

在使用SpringBoot时,我们经常会看到spring-boot-starter-*,这样的引入方式。那么starter到底是什么呢?官方解释为:*就是某种场景,是一组依赖的集合描述!例如,如果要开始使用Spring和JPA进行数据库访问,使用spring-boot-starter-data-jpa在项目中包含依赖项。

只要引入starter,这个场景的所有常规需要的依赖我们都自动引入。SpringBoot所有支持的场景。当然我们也可以自定义自己的starter。

官方地址:https://docs.spring.io/spring-boot/docs/2.3.9.RELEASE/reference/html/using-spring-boot.html#using-boot-starter

见到的 *-spring-boot-starter: 第三方(非官方)为我们提供的简化开发的场景启动器。

所有场景启动器最底层的依赖(自动配置核心依赖):

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.3.9.RELEASE</version>
  <scope>compile</scope>
</dependency>

3.2、自动配置

1、自动配好了Tomcat

  1. 引入依赖
  2. SpringBoot自动配置tomcat(关于自动配置原理,后面会详细介绍)
<!-- tomcat的依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-tomcat</artifactId>
  <version>2.3.9.RELEASE</version>
  <scope>compile</scope>
</dependency>

2、自动配好SpringMVC

  1. 引入SpringMVC的全套组件的依赖
  2. 自动配好SpringMVC常用组件(Web常见功能,如:字符编码问题)

例如:我们可以在主程序中,查看SpringBoot自动为我们配好的组件。

/**
 * @description: 主程序类
 * @author: laizhenghua
 * @date: 2021/3/23 21:39
 */
@SpringBootApplication // 标注SpringBoot应用
public class MainApplication {
    
    
    public static void main(String[] args) {
    
    
        // 1、返回IOC容器
        ConfigurableApplicationContext applicationContext = SpringApplication.run(MainApplication.class, args);

        // 2、查看容器里面的组件(组件名)
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        // System.out.println(Arrays.toString(beanNames));
        for(String name: beanNames) {
    
    
            System.out.println(name);
        }
    }
}

打印出的结果我们可以看到:有dispatcherServlet、characterEncodingFilter、beanNameViewResolver、multipartResolver等等,这些组件在以前我们都要在web.xml中逐一配置!现在SpringBoot全部给我们配置好了。

3.3、默认的包结构

在这里插入图片描述

  • 重点记忆:主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
  • 无需以前的包扫描配置
  • 想要改变扫描路径,@SpringBootApplication(scanBasePackages="com.atguigu")。或者@ComponentScan指定扫描路径
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")

3.4、各种配置拥有默认值

1、默认配置最终都是映射到某个类上,如:MultipartProperties.java

/**
 * Max file size.
 */
private DataSize maxFileSize = DataSize.ofMegabytes(1); // 1MB

// 文件上传最大可上传默认值(MultipartProperties.java代码节选)

2、配置文件的值最终会绑定每个类上,这个类会在容器中创建对象

# application.properties 配置文件里重新修改文件上传最大值
spring.servlet.multipart.max-file-size=10MB

3、按需加载所有自动配置项

  • 非常多的starter。
  • 引入了哪些场景这个场景的自动配置才会开启(自动配置按需加载)。
  • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面。

猜你喜欢

转载自blog.csdn.net/m0_46357847/article/details/115134083