001 第一季SpringBoot2核心技术-基础入门:分类,概念,入门案例:主启动类、配置文件,bulid插件,自动配置原理:父版本号、web依赖、包扫描、读取prop文件、热部署,boot项目

一、SpringBoot2学习路线说明

说明:SpringBoot2分为核心技术和响应式编程2大类。

  1. SpringBoot2核心技术
    基础篇:SpringBoot的快速掌握和基本原理。
    核心功能篇:配置文件,web开发,Juint5单元测试…
    场景整合:缓存技术,分布式入门…

  2. SpringBoot2响应式编程:SpringBoot以前的基础开发都可以使用另一套方案响应式编程来替代,所谓的响应式编程即:解决一个问题,如何使用少量的资源能编写一个极高的吞吐量,承担大并发的一个应用。
    响应式编程:是未来的流行趋势,spring一直在大力推广。
    在这里插入图片描述

1. SpringBoot2核心技术

在这里插入图片描述

2. SpringBoot2响应式编程

在这里插入图片描述

3. 学习前提

学习要求
● 熟悉Spring基础
● 熟悉Maven使用

环境要求
● Java8及以上
● Maven 3.3及以上

二、核心技术之- ->基础入门

1. Spring与SpringBoot

1.1 Spring能做什么

1.1.1 Spring的能力

  • Microservice微服务开发,开发一个项目里面的模块众多,把所有的模块都写在同一个项目中,显然不合适。可以把项目的所有功能拆分为一个个的微小模块,每个模块称为微服务。
  • Reactive响应式编程,基于异步非阻塞的方式,我们可以在每个应用之间构建异步流的方式来实现占用少量资源构建一个高吞吐量的应用。
  • Cloud分布式云开发,把项目拆分为微小模块后就会产生分布式应用,SpingCloud就要相关的解决方案。
  • Web AppsWeb开发,使用SpringMvc开发一个Web应用,接收请求 响应一个json数据、一个页面等。
  • Serverless无服务开发、函数即服务(FaaS:Function as a Service),简单快速的开发一个函数服务,我们无需购买服务器(这些服务器闲置的时候浪费资源),直接把函数服务上传到云平台,按量按时计费,这样可以减少很多人力、财力的浪费。
  • Event Driven事件驱动,Spring将整个分布式系统构建成一个实时的数据流(streaming data),有了数据流之后就可以通过响应式的方式让整个系统占用少量的资源完成高吞吐量的业务。
  • Batch批处理
    在这里插入图片描述

1.1.2 Spring的生态

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

  • 覆盖了:
  • web开发
  • 数据访问
  • 安全控制
  • 分布式
  • 消息服务
  • 移动开发
  • 批处理

1.1.3 Spring和SpringBoot的关系

说明

  1. Spring是一个轻量级的框架,可以整合Spring生态圈的一些列技术如:SpringMvc、SpringSecurity(安全控制) ,甚至是第三方的框架如Mybatis等。但是这些技术在整合的时候需要进行一系列的繁琐配置,太过麻烦。
  2. SpringBoot是对Spring的进一步封装,可以简化Spring开发的配置。
  3. eg:我们现在掌握了造内存、cpu、硬盘等技术,但是现在就是想要一台电脑那么如何把这些东西组装到一起呢,可以直接到品牌方如联想买一台电脑。

1.1.4 Spring5重大升级

1) 响应式编程

说明

  • Servlet开发、SpringMvc开发,数据层Spring Data开发、Spring Sercurity安全开发等、SpringBoot引入了2套解决方案
      1. Servlet Stack:原生Servlet技术栈,通过Spring SpringMvc来实现。
      1. Reactive Stack:响应式开发技术栈。

在这里插入图片描述

2) 内部源码设计:

基于Java8的一些新特性,如:接口默认实现(不用重写所有的接口方法)。重新设计源码架构。

1.2. 为什么用SpringBoot

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

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

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

1.2.2 SpringBoot缺点

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

1.3. 时代背景

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

1.3.2 分布式

在这里插入图片描述

1) 分布式的困难

说明:使用微服务把大型的软件拆分为一个个的微小服务,独立部署后会产生分布式的各种困难,比如部署到A服务器的模块Aa如何调用部署到B服务器的模块Bb呢,如何负载均衡呢?? 还有如下的一系列问题。

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

2) 分布式的解决

说明

  • 使用SpringBoot + SpringCloud进行开发。

在这里插入图片描述

1.3.3 云原生

说明:

  • 开发好后,如何部署呢?
  • 原生应用如何上云。 Cloud Native。

1) 上云的困难

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

2) 上云的解决

在这里插入图片描述

1.4. 如何学习SpringBoot

1.4.1 官网文档架构

Spring官网https://spring.io/
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
查看版本新特性:

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

在这里插入图片描述

2. SpringBoot2入门

说明:此版本基于SpringBoot2.3与2.4版本讲解。

2.1 系统要求

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

2.1.1 maven设置

说明:配置阿里云镜像,设置Maven使用jdk1.8进行项目编译。

<mirrors>
      <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
      </mirror>
  </mirrors>
 
  <profiles>
         <profile>
              <id>jdk-1.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 HelloWorld

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

2.2.1 创建maven工程

在这里插入图片描述

2.2.2 引入依赖

 <!--想要使用springboot的功能,就必须引入springboot的父项目-->
  <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.3.4.RELEASE</version>
   </parent>

   <dependencies>
    <!--想要开发web,就要引入web场景-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

   </dependencies>

2.2.3 创建主程序(主启动类)

在这里插入图片描述

/**
 * 主程序类:可以看成是一个主配置类,是所有启动的入口。(固定写法)
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(MainApplication.class,args);
    }
}

2.2.4 编写业务

在这里插入图片描述

//@ResponseBody
//@Controller

@RestController
public class HelloController {
    
    

    @RequestMapping("/hello")
    public String handle01(){
    
    
        return "Hello, Spring Boot 2!";
    }

}

2.2.5 测试(待定)

说明

  1. SpringMvc访问地址:ip:port/projectName/url,需要手动安装和配置Tomact服务器,url需要写上下文路径。
  2. SpringBoot访问地址:直接执行main函数来启动一个内置的Tomact服务器来处理请求,这时候访问默认是不需要添加项目名的,默认的context-path 是"/",加上项目名后会报404哦。

在这里插入图片描述
在这里插入图片描述

2.2.6 简化配置(properties配置文件)

说明:SpringBoot将之前Spring整合的一些列配置都抽取到了properties配置文件。

application.properties

server.port=8888 #修改服务器的端口号

在这里插入图片描述
在这里插入图片描述

2.2.7 简化部署(build插件 打jar包)

说明

  1. 项目不发布只能本地访问,发布到Tomact服务器之后别人也可以访问。
  2. 之前:想要接收用户请求并响应给浏览器页面或数据,使用web资源所以创建的是web项目,打包方式为war包。把打成war包的项目部署到服务器,服务器需要安装tomact等一大堆配置。
  3. 现在:只需要引入这个springboot给我们提供的一个插件,就可以直接把这个项目打成一个 jar包 ,这个jar包自带了我们整套的运行环境,我们可以直接运行。
  4. 总结:以前运行web项目需要把项目打包成war包,在服务器上部署后需要配置一系列的运行环境。现在使用了springboot提供的一个插件,即便是把web项目打成jar包,也可以部署到服务器上运行。
 <build>
     <plugins>
         <plugin>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
     </plugins>
   </build>

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

在这里插入图片描述
打开target文件所在的目录,并进入到target目录,可以看到打包好的jar包。
当然也可以直接复制这个jar包到一个磁盘目录运行。
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

注意点:

  • 取消掉cmd的快速编辑模式
    在这里插入图片描述

3. 了解自动配置原理

3.1 SpringBoot特点

3.1.1 依赖管理(父版本号 场景启动器)

  • 父项目做依赖管理
<!--依赖管理:每一个SpringBoot工程都有一个父项目parent    -->
<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.3.4.RELEASE</version>
</parent>

<!--parent的父项目:dependencies
   几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制-->
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>
  
  • 开发导入starter场景启动器
<!--
1、官方见到很多 spring-boot-starter-* : *就代表某种场景
2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
3、SpringBoot所有支持的场景:官方文档的地址可以查看所有的SpringBoot所有支持的场景
		https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
4、见到的  *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
5、所有场景启动器最底层的依赖:starter  -->

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

3.1.2 自动配置(web依赖、包扫描)

  • 自动配好Tomcat
    ○ 引入Tomcat依赖
    ○ 配置Tomcat
    ○ 说明:引入web依赖就会自动引入Tomcat依赖,并自动配置好。
    在这里插入图片描述
    在这里插入图片描述
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>2.3.4.RELEASE</version>
    <scope>compile</scope>
</dependency>
  • 自动配好SpringMVC
    ○ 引入SpringMVC全套组件
    ○ 自动配好SpringMVC常用组件(功能)
    ○ 说明:同样引入web依赖也会引入SpringMVC全套组件,并自动配置好。在这里插入图片描述
    在这里插入图片描述
package com.atguigu.boot;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

/**
 * 主程序类
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@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) {
    
    
            System.out.println(name);
        }

    }
}

在这里插入图片描述

  • 自动配好Web常见功能,如:字符编码问题
    ○ SpringBoot帮我们配置好了所有web开发的常见场景
    在这里插入图片描述
    在这里插入图片描述

  • 默认的包结构即:默认的包扫描
    ○ 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
    ○ 无需以前的包扫描配置
    ○ 想要改变扫描路径,@SpringBootApplication(scanBasePackages=“com.atguigu”)

    • 或者@ComponentScan 指定扫描路径(因为@SpringBootApplication底层包含的有@ComponentScan注解,注解不能重复,所以这2个注解不能同时使用
      在这里插入图片描述
      在这里插入图片描述
@SpringBootApplication //合成注解
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
  • 各种配置拥有默认值
    ○ 默认配置最终都是映射到某个类上,如:MultipartProperties(文件上传的最大值)
    ○ 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
    在这里插入图片描述
    在这里插入图片描述

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

3.2 容器功能

准备实体类:
在这里插入图片描述
在这里插入图片描述

3.2.1 组件添加

1) @Configuration+@Bean (@Configuration配置单例多例)

说明:代替之前的spring框架中的xml方式创建对象

原先写法:
在这里插入图片描述

  • 基本使用
  • Full模式与Lite模式
    • 示例
    • 使用场景:
      • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式(单实例)
      • 配置类组件之间无依赖关系,用Lite模式加速容器启动过程,减少判断(多实例)

测试步骤:

添加依赖关系:
在这里插入图片描述
配置类:
在这里插入图片描述
主启动类:
在这里插入图片描述

#############################Configuration使用示例######################################################
/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、配置类本身也是组件
 * 3、proxyBeanMethods:代理bean的方法
 *     Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】---默认
 *     Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
 * 使用场景:组件之间有依赖关系,为了保证依赖调用的是同一个组件,使用Full模式(单实例)
 *         组件之间没有依赖关系,用`Lite模式`加速容器启动过程,减少判断(多实例)
 *
 *
 */
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == xml配置文件
public class MyConfig {
    
    

    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
    
    
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件,只有是true的情况Full模式单实例,此时才能保证用到的是
        //     用户用到的宠物和容器中下面注册的组件宠物是同一个。
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom")//自定义Bean的名字
    public Pet tomcatPet(){
    
    
        return new Pet("tomcat");
    }
}


################################@Configuration测试代码如下########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
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) {
    
    
            System.out.println(name);
        }

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

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

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

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


        //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);

        //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
        //保持组件单实例
        User user = bean.user01();
        User user1 = bean.user01();
        System.out.println(user == user1);


        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);
		
		//如果是Full模式,此时用户用到的宠物组件就是容器中注册的宠物组件,输出为true
		//如果是Lite模式,此时用户用到的宠物组件和容器中注册的宠物组件不是同一个,输出为false
        System.out.println("用户的宠物:"+(user01.getPet() == tom));



    }
}

2) @ComponentScan+@Component @Controller @Service @Repository

说明:之前的spring框架的注解方式创建对象,仍然可以使用。即:包扫描+注解方式,只不过包扫描现在默认是主启动类所在的包以及其子包中,当然也可修改包扫描的路径,2种方式修改。

3) @Import

  • @Import:给容器中导入一个组件,可以写在任何一个配置类或组件(controller、srvice…)里面 spring注解驱动开发讲过了,略。
/**
 * 4、@Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件(对象)、默认组件的名字就是全类名
 *      可以是自己创建的类,也可以是引入的第三方jar包里面的类
 */
@Import({
    
    User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {
    
    
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

@Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8

4) @Conditional(按条件注册)

条件装配:满足Conditional指定的条件,则进行组件注入
在这里插入图片描述
测试:
配置类:
在这里插入图片描述
主启动类:
在这里插入图片描述

=====================测试条件装配==========================
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom") //加在类上,当条件成立时,下边的所有配置才生效。
@ConditionalOnMissingBean(name = "tom") //容器中没有tom时,添加组件
public class MyConfig {
    
    


    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */

    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    //@ConditionalOnBean(name = "tom")//加在方法上,当满足条件时,组件才会被注册到容器中
    public User user01(){
    
    
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom22")
    public Pet tomcatPet(){
    
    
        return new Pet("tomcat");
    }
}
----------------------主启动类---------------------
public static void main(String[] args) {
    
    
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);

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

        boolean tom = run.containsBean("tom");
        System.out.println("容器中Tom组件:"+tom);

        boolean user01 = run.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);

        boolean tom22 = run.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);
    }

3.2.2 原生配置文件引入

说明:公司里面很对老项目使用的还是xml方式注册组件,现在一个个的改为注解方式太麻烦,可以在配置类中使用@ImportResource注解直接把xml文件解析放到容器中。

1) @ImportResource

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

======================beans.xml=========================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <bean id="haha" class="com.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>
/**
 *
 * 5、@ImportResource("classpath:beans.xml")导入Spring的配置文件
 */
@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

3.2.3 配置绑定(读取properties文件)

说明:把经常变化的东西配置到配置文件中,比如数据库连接信息,之后在一一解析到JavaBean中,这个过程如果用原生的java代码实现会非常麻烦,springboot提供了对应的注解进行实现。。

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;

//原生方式:使用java代码读取
public class getProperties {
    
    
     public static void main(String[] args) throws FileNotFoundException, IOException {
    
    
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
    
    
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

1) @Component + @ConfigurationProperties

配置文件:
在这里插入图片描述

实体类:
在这里插入图片描述
测试:启动主启动类,访问控制层方法路径。
在这里插入图片描述
在这里插入图片描述

mycar.brand=YD
mycar.price=100000
---------------------------------------------
package com.atguigu.boot.bean;

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

/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能,所以要加上@Component。
 * prefix 前缀:指的是类里面的每一个属性跟配置文件哪个前缀下的属性一一绑定。
 *  里面的属性名要保持一致
 */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
    
    
    private String brand;
    private Integer price;

    public Car() {
    
    
    }

    public Car(String brand, Integer price) {
    
    
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
    
    
        return brand;
    }

    public void setBrand(String brand) {
    
    
        this.brand = brand;
    }

    public Integer getPrice() {
    
    
        return price;
    }

    public void setPrice(Integer price) {
    
    
        this.price = price;
    }

    @Override
    public String toString() {
    
    
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}
-------------------------------------------
@RestController
public class HelloController {
    
    

    @Autowired
    Car car;


    @RequestMapping("/car")
    public Car car(){
    
    
        return car;
    }


}

2) @EnableConfigurationProperties + @ConfigurationProperties

说明:因为实体类可能用的是第三方包里面的,可能没有加@Component,你也不能擅自加上,此时就可以使用这种方式。

修改实体类:
在这里插入图片描述
修改配置类:
注意:此注解@EnableConfigurationProperties一定要写在配置类中,因为配置类属于容器中的组件,在配置类上写才能生效。
在这里插入图片描述

1、开启Car配置绑定功能
2、把这个Car这个组件自动注册到容器中
@EnableConfigurationProperties(Car.class)

仍然访问成功:
在这里插入图片描述

3.3 自动配置原理入门

3.3.1 引导加载自动配置类(@SpringBootApplication)

在这里插入图片描述

//主启动类的@SpringBootApplication注解,相当于以下3个注解的组合。
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
    
     @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{
    
    }


======================

1) @SpringBootConfiguration

此注解的底层是@Configuration。代表当前是一个配置类
在这里插入图片描述

2) @ComponentScan

指定扫描哪些,Spring注解;具体查看spring注解驱动开发。

3) @EnableAutoConfiguration

它也是个合成注解

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

在这里插入图片描述

3.1) @AutoConfigurationPackage

自动配置包?指定了默认的包规则
在这里插入图片描述

@Import(AutoConfigurationPackages.Registrar.class)  //给容器中导入一个组件
public @interface AutoConfigurationPackage {
    
    }

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

在这里插入图片描述

文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3.3.2 按需开启自动配置项

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

3.3.3 修改默认配置(自动配置流程)

@Bean
@ConditionalOnBean(MultipartResolver.class)  //容器中有这个类型组件
@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
public MultipartResolver multipartResolver(MultipartResolver resolver) {
    
    
//给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
//SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
// Detect if the user has created a MultipartResolver but named it incorrectly
	return resolver;
}
给容器中加入了文件上传解析器;

SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先

@Bean
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
    
    
    }

总结:

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

3.3.4 最佳实践(debug=true,banner图)

3.4 开发小技巧

3.4.1 Lombok

说明:简化JavaBean开发,可以简写get、set、构造方法等等,程序在编译的时候会自动生成对应的方法。

步骤1:首先引入依赖:

  <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
  </dependency>

步骤2:idea中搜索安装lombok插件
在这里插入图片描述

在这里插入图片描述

===============================简化JavaBean开发===================================
package com.atguigu.boot.bean;

import lombok.*;

//@AllArgsConstructor //全参构造器
@NoArgsConstructor  //无参构造器
@Data //生成setter/getter、equals、canEqual、hashCode、toString方法,若为final属性,则不会为该属性生成setter方法。
@ToString //用于为描述的类添加toString方法。
@EqualsAndHashCode //用于为描述的类,生成hashCode和equals方法。
public class User {
    
    
    private String name;
    private Integer age;
    private Pet pet;

    public User(String name, Integer age) {
    
    
        this.name = name;
        this.age = age;
    }
}



================================简化日志开发===================================
@Slf4j //代替日志属性log 
@RestController
public class HelloController {
    
    

 //private static final Logger log = LoggerFactory.getLogger(UserLog.class);//当前类.class
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
    
    
        
        log.info("请求进来了....");
        
        return "Hello, Spring Boot 2!"+"你好:"+name;
    }
}

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

3.4.2 dev-tools(热部署)

说明:配置热部署。(这是重启)

步骤1:引入依赖。

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

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

说明:如果想要纯正的热更新技术,可以再idea中安装付费的插件JRebel,只要内容变化它就会重新启动。(这是重加载)

3.4.3 Spring Initailizr(项目初始化向导)

说明:开发springboot应用,开发什么场景需要引入对应的依赖,还要参照官方文档查看需要支持那些场景,之后创建Maven工程把依赖引入进来。现在indea或者eclipse提供了Spring Initailizr。可以帮助我们快速的创建springboot项目。
在这里插入图片描述
在这里插入图片描述

1) 选择我们需要的开发场景

注意SpringBoot3.0开始需要使用jdk17开始的版本。
在这里插入图片描述
在这里插入图片描述

2) 自动依赖引入

在这里插入图片描述

3) 自动创建项目结构

引入web依赖会自动创建

说明

  • static目录下的资源可以直接在浏览器输入地址进行访问。
  • 模板引擎templates目录下所有页面的解析必须要经过请求处理(编写控制层方法),最终由模板引擎进行解析的。

在这里插入图片描述

4) 自动编写好主配置类

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/aa35434/article/details/123767220