SpringBoot完整技能汇总

饭宝  金牌会员 | 2024-12-20 01:17:02 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 890|帖子 890|积分 2670

SpringBoot

   留意:SpringBoot技能示例中的项目均已上传至Gitee,均可通过此处自行下载
  

  • SpringBoot是由Pivotal团队提供的全新框架,其计划目标是用来简化Spring应用的初始搭建以及开发过程
  • Spring程序与SpringBoot程序对比如下


    • Spring程序设置以及依赖设置繁琐
    • SpringBoot程序自动设置,并简化了依赖设置(即具有起步依赖),除此之外还添加了辅助功能(比如内置了服务器)

  • 留意

    • SpringBoot在创建项目时,接纳的是jar包的方式
    • SpringBoot的引导类是项目标入口,运行main方法即可启动项目

      • 引导类名为项目名+Application,以快速入门为例,即SpringBootDemoApplication


SpringBoot快速入门



  • 并不是全部的IDE均可创建SpringBoot项目框架

    • 基于idea开发SpringBoot程序需要确保联网且可以或许加载到程序框架布局
    • 别的IDE开发SpringBoot程序需要进入SpringBoot官网来加载程序框架布局

idea创建方式



  • Step1:

  • Step2: 若创建的是Web项目标话则按下图步骤创建即可;反之则清除10、11两步即可

  • Step3: 创建完成后初始SpringBoot项目框架目录如图所示

  • Step4: 在at.guigu包下创建表现层controller包,并在该包下创建BookController类,代码如下
    1. package at.guigu.controller;
    2. import org.springframework.web.bind.annotation.GetMapping;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.bind.annotation.RestController;
    6. @RestController
    7. @RequestMapping("/books")
    8. public class BookController {
    9.     @GetMapping("/{id}")
    10.     public String getById(@PathVariable(value = "id") Integer id) {
    11.         System.out.println("id===>" + id);
    12.         return "Hello SpringBoot!!!";
    13.     }
    14. }
    复制代码
  • Step5: 运行SpringBoot的引导类SpringBootDemoApplication,该项目即可启动成功,如图所示


  • Step6: 利用Postman测试

    • 前端页面显示

    • idea控制台显示


别的ide创建方式



  • Step1: 进入到SpringBoot官网,选择Quickstart Your Project,如图所示

  • Step2: 若创建的是Web项目标话则按下图步骤创建即可;反之则清除8、9两步即可

  • Step3: 然后就会生成一个包含SpringBoot项目标压缩包,解压后Import导入项目即可(此步不在演示)
SpringBoot项目快速启动



  • SpringBoot可用于前后端分聚散作开发

    • 传统项目下后端人员做完项目后,前端人员若想使用则必须连后端人员的电脑才能使用,为解决这个弊端,SpringBoot可以将项目打包成jar包传给前端人员,且该jar包与后端人员连接同一个数据库,此时即可使项目不依赖Tomcat等情况运行


  • Step1: 执行Maven构建指令package来对SpringBoot项目举行打包
           留意:在执行Maven构建指令package来对SpringBoot项目举行打包前,最好执行一下clean指令,以此来避免不必要的贫苦
       

  • Step2: 将jar包发给前端人员(此处在博主电脑上举行示例),然后在文件地点位置通过cmd打开命令窗口,输入指令java -jar SpringBoot的jar包名.jar

    • 留意:若通过命令窗口报错:java.lang.UnsupportedClassVersionError: org/springframework/boot/loader/launch/JarLauncher has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0,说明你的jdk版本过低无法运行当前SpringBoot项目,则需要升级jdk版本,由于博主设置了jdk1.8和jdk21两个jdk版本,以是设置暂时情况变量的步骤如下:

      • Step1:将jdk版本暂时切换为jdk21:set JAVA_HOME1=F:\app\jdk-21,后为本身的jdk安装路径
      • Step2:使用set PATH=%JAVA_HOME1%\bin;%PATH%指令让暂时情况变量生效
      • Step3:输入指令java -jar SpringBoot的jar包名.jar 运行SpringBoot项目标jar包即可,如图所示



  • Step3: 利用Postman测试

    • 前端页面显示

    • 命令窗口显示


  • 留意

    • 在执行Maven构建指令package来对SpringBoot项目举行打包前,最好执行一下clean指令,以此来避免不必要的贫苦
    • jar包支持命令行启动需要依赖maven插件支持,以是在打包前需要确认SpringBoot项目标pom.xml文件中是否具有SpringBoot对应的maven插件,若不存在则添加即可,插件代码如下
      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>
      复制代码
    • 设置文件中若存在中文可能会打包失败,则解决步骤如下:

      • Step1: 将IDE编码格式均改为UTF-8

      • Step2: 关闭设置文件,然后重新打开设置文件,看是否有乱码,若有则将乱码删除重新写一下即可。


pom.xml文件解析

   快速入门中SpringBoot项目SpringBootDemo的pom.xml文件初始代码如下
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.     <modelVersion>4.0.0</modelVersion>
  5.     <parent>
  6.         <groupId>org.springframework.boot</groupId>
  7.         <artifactId>spring-boot-starter-parent</artifactId>
  8.         <version>3.4.0</version>
  9.         <relativePath/> <!-- lookup parent from repository -->
  10.     </parent>
  11.     <groupId>org.example</groupId>
  12.     <artifactId>SpringBootDemo</artifactId>
  13.     <version>0.0.1-SNAPSHOT</version>
  14.     <name>SpringBootDemo</name>
  15.     <description>SpringBootDemo</description>
  16.     <url/>
  17.     <licenses>
  18.         <license/>
  19.     </licenses>
  20.     <developers>
  21.         <developer/>
  22.     </developers>
  23.     <scm>
  24.         <connection/>
  25.         <developerConnection/>
  26.         <tag/>
  27.         <url/>
  28.     </scm>
  29.     <properties>
  30.         <java.version>21</java.version>
  31.     </properties>
  32.     <dependencies>
  33.         <dependency>
  34.             <groupId>org.springframework.boot</groupId>
  35.             <artifactId>spring-boot-starter-web</artifactId>
  36.         </dependency>
  37.         <dependency>
  38.             <groupId>org.springframework.boot</groupId>
  39.             <artifactId>spring-boot-starter-test</artifactId>
  40.             <scope>test</scope>
  41.         </dependency>
  42.     </dependencies>
  43.     <build>
  44.         <plugins>
  45.             <plugin>
  46.                 <groupId>org.springframework.boot</groupId>
  47.                 <artifactId>spring-boot-maven-plugin</artifactId>
  48.             </plugin>
  49.         </plugins>
  50.     </build>
  51. </project>
复制代码


  • 该pom.xml文件中用到的关键词

    • starter:SpringBoot中常见项目名称,定义了当前项目使用的全部项目坐标,以达到淘汰依赖设置的目标
    • parent:

      • 全部SpringBoot项目要继续的项目,定义了多少个坐标版本号(依赖管理,而非依赖),以达到淘汰依赖辩论的目标
      • spring-boot-starter-parent(2.5.0)与 spring-boot-starter-parent(2.4.6)共计57处坐标版本不同


  • SpringBootDemo的pom.xml文件有聚合工程(即父工程),父工程名为spring-boot-starter-parent如下:
    1. <parent>
    2.     <groupId>org.springframework.boot</groupId>
    3.     <artifactId>spring-boot-starter-parent</artifactId>
    4.     <version>3.4.0</version>
    5.     <relativePath/> <!-- lookup parent from repository -->
    6. </parent>
    复制代码
  • SpringBootDemo的pom.xml文件中的依赖均为起步依赖(即需要什么就导入对应的起步依赖,起步依赖均有一个starter标志)

    • 若该项目为web工程(即做web开发),则导入web工程的起步依赖
    • 若该项目需要测试,则导入测试的起步依赖
    • 默认情况下SpringBoot项目标pom.xml文件在初始状态下就有以下两个起步依赖
    1. <dependencies>
    2.     <!--web项目的起步依赖-->
    3.     <dependency>
    4.         <groupId>org.springframework.boot</groupId>
    5.         <artifactId>spring-boot-starter-web</artifactId>
    6.     </dependency>
    7.         <!--测试的起步依赖-->
    8.     <dependency>
    9.         <groupId>org.springframework.boot</groupId>
    10.         <artifactId>spring-boot-starter-test</artifactId>
    11.         <scope>test</scope>
    12.     </dependency>
    13. </dependencies>
    复制代码

  • 留意

    • 在现实开发中,本身SpringBoot项目标pom.xml文件中的依赖均泉源于spring-boot-dependencies的pom.xml文件中所设置的可选依赖,这也就是为什么本身的pom.xml文件中存在的两个初始依赖不需要设置版本的原因
    • 在现实开发中,用户需要什么,就导入对应的起步依赖即可,因为该依赖内部已设置好对应的内容,用户使用即可。这也就是为什么博主在快速入门中没有导入一些列Spring、SpringMvc以及Tomcat等坐标依赖还能成功运行原因
    • 在现实开发中使用任意坐标时,仅誊写GAV中的G和A,V由SpringBoot提供。若发生坐标错误,再指定version(要小心版本辩论)

  • Jetty相对于Tomcat来说更轻量级,可扩展性更强,且谷歌应用引擎(GAE)已经全面切换为Jetty,以是我们在创建SpringBoot项目时可自行在web项目标起步依赖中清除使用Tomcat依赖,转而使用Jetty依赖,步骤如下:

    • Step1: 利用<exclusions>标签清除Tomcat依赖
      1. <dependencies>
      2.     <dependency>
      3.         <groupId>org.springframework.boot</groupId>
      4.         <artifactId>spring-boot-starter-web</artifactId>
      5.         <exclusions>
      6.             <exclusion>
      7.                 <groupId>org.springframework.boot</groupId>
      8.                 <artifactId>spring-boot-starter-tomcat</artifactId>
      9.             </exclusion>
      10.         </exclusions>
      11.     </dependency>
      12.     <dependency>
      13.         <groupId>org.springframework.boot</groupId>
      14.         <artifactId>spring-boot-starter-test</artifactId>
      15.         <scope>test</scope>
      16.     </dependency>
      17. </dependencies>
      复制代码
                留意:若不知道Tomcat依赖的groupId和artifactId,可进入到spring-boot-starter-web的pom.xml文件中找,如图所示
            

    • Step2: 添加Jetty依赖

      • 由于SpringBoot的聚合工程的聚合工程(即父工程的父工程)提供的可选依赖中存在该Jett依赖,以是添加时仅誊写GAV中的G和A,而V由SpringBoot提供
      1. <dependency>
      2.     <groupId>org.springframework.boot</groupId>
      3.     <artifactId>spring-boot-starter-jetty</artifactId>
      4. </dependency>
      复制代码
                留意:若不知道Jetty依赖的groupId和artifactId,可进入到spring-boot-starter-web的pom.xml文件中找,如图所示
            



  • 此时快速入门中创建的SpringBoot项目标pom.xml文件完整代码如下
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.     <modelVersion>4.0.0</modelVersion>
    5.     <parent>
    6.         <groupId>org.springframework.boot</groupId>
    7.         <artifactId>spring-boot-starter-parent</artifactId>
    8.         <version>3.4.0</version>
    9.         <relativePath/> <!-- lookup parent from repository -->
    10.     </parent>
    11.     <groupId>org.example</groupId>
    12.     <artifactId>SpringBootDemo</artifactId>
    13.     <version>0.0.1-SNAPSHOT</version>
    14.     <name>SpringBootDemo</name>
    15.     <description>SpringBootDemo</description>
    16.     <url/>
    17.     <licenses>
    18.         <license/>
    19.     </licenses>
    20.     <developers>
    21.         <developer/>
    22.     </developers>
    23.     <scm>
    24.         <connection/>
    25.         <developerConnection/>
    26.         <tag/>
    27.         <url/>
    28.     </scm>
    29.     <properties>
    30.         <java.version>21</java.version>
    31.     </properties>
    32.     <dependencies>
    33.         <dependency>
    34.             <groupId>org.springframework.boot</groupId>
    35.             <artifactId>spring-boot-starter-web</artifactId>
    36.             <exclusions>
    37.                 <exclusion>
    38.                     <groupId>org.springframework.boot</groupId>
    39.                     <artifactId>spring-boot-starter-tomcat</artifactId>
    40.                 </exclusion>
    41.             </exclusions>
    42.         </dependency>
    43.         <!--配置Jetty坐标依赖-->
    44.         <dependency>
    45.             <groupId>org.springframework.boot</groupId>
    46.             <artifactId>spring-boot-starter-jetty</artifactId>
    47.         </dependency>
    48.         <dependency>
    49.             <groupId>org.springframework.boot</groupId>
    50.             <artifactId>spring-boot-starter-test</artifactId>
    51.             <scope>test</scope>
    52.         </dependency>
    53.     </dependencies>
    54.     <build>
    55.         <plugins>
    56.             <plugin>
    57.                 <groupId>org.springframework.boot</groupId>
    58.                 <artifactId>spring-boot-maven-plugin</artifactId>
    59.             </plugin>
    60.         </plugins>
    61.     </build>
    62. </project>
    复制代码
    成功运行后截图如下

聚合工程(即父工程)的pom文件



  • SpringBootDemo的pom.xml文件有聚合工程(即父工程),父工程名为spring-boot-starter-parent,该父工程的pom.xml文件中重要有四部门内容:

    • spring-boot-starter-parent也存在聚合工程(父工程),即spring-boot-dependencies
    • 开启资源文件目录加载属性的过滤器
    • 插件设置
    • 多情况设置


  • spring-boot-dependencies的pom.xml文件中重要有三部门内容

    • 多情况设置
    • 可选依赖

      • 本身所创建的SpringBoot项目标依赖都是泉源于该工程下

    • 插件设置

       

    • 留意:本身的初始pom.xml文件中对应的起步依赖就在该聚合工程spring-boot-dependencies的可选依赖中设置的。现实开发过程中,本身需要什么,就导入对应的起步依赖即可。这也就是为什么博主在快速入门中没有导入一些列Spring、SpringMvc以及Tomcat等坐标依赖还能成功运行原因
    • SpringBoot的有些起步依赖为辅助功能,因为这些依赖并不是为程序员开发程序提供业务功能的,而是资助启动的。比如博主的初始pom.xml中的web起步依赖,就是为了程序运利用用的,它就是一个辅助功能

SpringBoot底子设置

   以快速入门的SpringBoot项目为例
  设置文件格式



  • SpringBoot提供了三种设置文件,分别为

    • application.properties(默认)
    • application.yml(现实开发项目中重要用该格式的设置文件)
    • application.yaml
    • 若三种形式的设置文件均存在于项目中,则此时properties为主启动设置文件,yml为次设置文件,yaml为最次设置文件,即加载次序优先级为application.properties>application.yml>application.yaml
    • 若三种格式的设置文件均存在于项目中且设置内容均同等,只有属性值不同,则优先级最高的生效,可详见SpringBoot多情况开发设置的快速入门部门内容
    • 在以上三种设置文件中设置内容时SpringBoot均会给出提示

  • 若设置文件未给出提示,则需要举行设置,步骤如图所示


    • 留意:若上图的Modules对应的SpringBoot项目下不存在Spring,则按下图所示步骤创建即可


   三种设置文件以修改服务器端口为例举行演示
  SpringBoot默认服务器端口为8080,如快速入门http://localhost:8080/books/1,将其端口号改为80,即http://localhost/books/1
  

  • 方式一: 打开源代码设置文件目录(即资源文件resources)下的application.properties文件,该文件初始代码如图所示


    • 添加端口设置,文件完整代码如下
      1. spring.application.name=SpringBootDemo
      2. server.port=80
      复制代码
    • 此时运行后,后端控制台截图如下


  • 方式二: 在源代码设置文件目录(即资源文件resources)下创建application.yml文件,完整代码如下
           留意:yml文件中的参数前必须要有空格,否则设置不成功
       
    1. server:
    2.   port: 81
    复制代码

  • 方式三: 在源代码设置文件目录(即资源文件resources)下创建application.yaml文件,完整代码如下
           留意:yml文件中的参数前必须要有空格,否则设置不成功
       
    1. server:
    2.   port: 82
    复制代码

yaml格式



  • YAML(YAML Ain’t Markup Language),一种数据序列化格式
  • 优点:

    • 容易阅读
    • 容易与脚本语言交互
    • 以数据为核心,重数据轻格式

  • YAML文件扩展名

    • .yml(主流)
    • .yaml

  • yaml语法规则

    • 巨细写敏感
    • 属性层级关系使用多行形貌,每行结尾使用冒号:结束

      • 比如我有个三级属性a.b.c=111,则除含属性值的属性外,前两级属性用:结束,代码表示如下:
        1. a:
        2. b:
        3.   c: 111
        复制代码
      • 假设我有两个三级属性a.b.c=111和a.b.d=222,则c和d同级,代码表示如下:
        1. a:
        2. b:
        3.   c: 111
        4.   d:222
        复制代码

    • 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)
    • 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)
    • #表示注释
    • 核心规则:数据前面要加空格与冒号隔开

  • yaml数组数据: 数组数据在数据誊写位置的下方使用减号-作为数据开始符号,每行誊写一个数据,减号与数据间空格分隔,代码表示如下:
    1. a:
    2.   b:
    3.     c: 111
    4.     d: 222
    5.     array:
    6.       - music
    7.       - game
    复制代码
yaml数据读取



  • yaml数据读取有三种方式

    • 方式一:利用@Value("${}")读取

      • 属性名引用方式:${一级属性名.二级属性名……}

    • 方式二:将数据全部封装到Environment对象
    • 方式三:创建自定义的对象来封装数据(常用)

      • 使用该方式时可能会有自定义对象封装数据警告,则在本身的pom.xml文件中引入以下依赖即可解决
                       该依赖存在于聚合工程的聚合工程(即父工程的父工程)spring-boot-dependencies的pom.xml文件的可选依赖中,以是不需导入版本号
              
        1. <dependency>
        2.     <groupId>org.springframework.boot</groupId>
        3.     <artifactId>spring-boot-configuration-processor</artifactId>
        4.     <optional>true</optional>
        5. </dependency>
        复制代码


  • 可能用到的接口及方法
       接口解释EnvironmentSpring 中的一个重要组件,用于处理和访问应用程序的情况变量设置属性Environment接口方法解释String getProperty(String key)用于获取指定属性的值,如果属性不存在返回 nullString getProperty(String key, String defaultValue)用于获取指定属性的值,如果属性不存在返回 默认值String resolvePlaceholders(String text)解析字符串中的占位符(${})。如果占位符没有对应的值,会抛出异常。String resolveRequiredPlaceholders(String text)解析字符串中的占位符(${})。如果占位符没有对应的值,会抛出IllegalArgumentException异常<T> T getProperty(String key, Class<T> targetType)将指定的属性值转换为目标类型返回,如果属性不存在返回 null<T> T getProperty(String key, Class<T> targetType, T defaultValue)将指定的属性值转换为目标类型返回,如果属性不存在返回 默认值boolean containsProperty(String key)判断是否存在指定属性String[] getActiveProfiles()获取当前激活的情况的 Profiles,通常用于区分开发、测试、生产情况String[] getDefaultProfiles()获取默认情况的的 Profiles(当未激活任何 Profiles 时使用)PropertySources getPropertySources()返回全部属性源(PropertySource 的聚集),可以获取具体的属性泉源Environment接口的子接口解释ConfigurableEnvironmentConfigurableEnvironment方法解释void addFirst(PropertySource<?> propertySource)将自定义的属性源添加到属性源聚集的首位,优先级最高void addLast(PropertySource<?> propertySource)将自定义的属性源添加到属性源聚集的末尾,优先级最低。
  • 可能用到的Spring的注解(Spring注解解释及示例可详见Spring部门内容)
       注解解释@Value注入平凡属性@Component使用在类上,用于实例化bean
  • 可能用到的SpringBoot的注解
       注解解释@ConfigurationProperties用于将外部设置(如 application.properties 或 application.yaml)中的属性值映射到 Spring 管理的 Java Bean 中@ConfigurationProperties属性解释prefix或value用于指定设置文件中需要绑定的属性前缀。只有以该前缀开头的设置项会被绑定到对应的 Java 类中ignoreUnknownFieldsSpringBoot 是否会忽略设置文件中没有在 Java 类中定义的属性。默以为true;若为false,此时若存在没有在 Java 类中定义的属性则会报错ignoreInvalidFields是否忽略类型不匹配的字段,默以为true       @ConfigurationProperties注解不能直接读取设置文件中全部属性的值,是基于前缀绑定的注解,要求指定一个属性前缀(prefix)来将相关的设置项绑定到类的字段。
        也就是说该注解不能直接绑定整个设置文件中的全部属性,只能按指定的前缀绑定特定的部门。可详见第三种方式示例

    • prefix或value

      • 该属性的属性值只能有一个,否则报错,具体示例可见第三种方式示例

    • ignoreUnknownFields示例

    • ignoreInvalidFields示例


   以下代码示例只举行关键步骤演示,其余步骤可详见快速入门部门内容
  

  • 两种方式公用的yaml设置文件代码内容如下
    1. server:
    2.   port: 82
    3. name: zhangsana:  b:    c: 111    d: 222    arrayOne:      - music      - gamee:  arrayTwo:    - 你好    - nihao
    复制代码
前两种方式示例



  • yaml数据读取方式: controller包下的BookController类代码更改如下:
    1. package at.guigu.controller;
    2. import org.springframework.beans.factory.annotation.Value;
    3. import org.springframework.web.bind.annotation.GetMapping;
    4. import org.springframework.web.bind.annotation.PathVariable;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. @RestController
    8. @RequestMapping("/books")
    9. public class BookController {
    10.     @Value("${name}")
    11.     private String name;
    12.     @Value("${a.b.c}")
    13.     private Integer c;
    14.     @Value("${a.b.arrayOne[0]}")
    15.     private String arrOne;
    16.     @Value("${e.arrayTwo[0]}")
    17.     private String arrTwo;
    18.     @GetMapping("/{id}")
    19.     public String getById(@PathVariable(value = "id") Integer id) {
    20.         System.out.println("id===>" + id);
    21.         System.out.println("name===>" + name);
    22.         System.out.println("c===>" + c);
    23.         System.out.println("arrOne===>" + arrOne);
    24.         System.out.println("arrTwo===>" + arrTwo);
    25.         return "Hello SpringBoot!!!";
    26.     }
    27. }
    复制代码
    运行截图如下

  • 数据全部封装到Environment对象的方式: 在controller包下创建BookControllerTwo类,代码如下:
    1. package at.guigu.controller;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.core.env.ConfigurableEnvironment;
    4. import org.springframework.core.env.Environment;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.PathVariable;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. @RestController
    10. @RequestMapping("/booksTwo")
    11. public class BookControllerTwo {
    12.     @Autowired
    13.     private Environment environment;
    14.     @GetMapping("/{id}")
    15.     public String getById(@PathVariable(value = "id") Integer id) {
    16.         System.out.println("id===>" + id);
    17.         System.out.println(environment.getProperty("name"));
    18.         System.out.println(environment.getProperty("a.b.c"));
    19.         System.out.println(environment.getProperty("a.b.arrayOne[0]"));
    20.         System.out.println(environment.getProperty("e.arrayTwo[0]"));
    21.         System.out.println("--------------------------------");
    22.         System.out.println(environment.resolvePlaceholders("d的属性值为:${a.b.d}"));
    23.         System.out.println("--------------------------------");
    24.         System.out.println(environment.resolveRequiredPlaceholders("post的属性值为:${server.port}"));
    25.         return "Hello SpringBoot!!!";
    26.     }
    27. }
    复制代码
    运行截图如下

第三种方式示例(常用)



  • Step1: 在at.guigu包下创建pojo包,并在该包中创建Enterprise类,然后在该类中创建设置文件中对应的属性,代码如下:

    • Step1-1: 用@Component修饰该类
    • Step1-2: 利用@ConfigurationProperties注解的prefix属性指定一个属性前缀来将相关的设置项对应的属性值绑定到类的字段。
                 留意:该类中的字段名要与设置文件中对应前缀的属性名称同等,否之无法获取到对应的属性值
    1. package at.guigu.pojo;
    2. import org.springframework.boot.context.properties.ConfigurationProperties;
    3. import org.springframework.stereotype.Component;
    4. import java.util.Arrays;
    5. @Component
    6. @ConfigurationProperties(prefix = "a.b")
    7. public class Enterprise {
    8.     private int c;
    9.     private int d;
    10.     private String[] arrayOne;
    11.     public int getC() {
    12.         return c;
    13.     }
    14.     public void setC(int c) {
    15.         this.c = c;
    16.     }
    17.     public int getD() {
    18.         return d;
    19.     }
    20.     public void setD(int d) {
    21.         this.d = d;
    22.     }
    23.     public String[] getArrayOne() {
    24.         return arrayOne;
    25.     }
    26.     public void setArrayOne(String[] arrayOne) {
    27.         this.arrayOne = arrayOne;
    28.     }
    29.     @Override
    30.     public String toString() {
    31.         return "Enterprise{" +
    32.                 "c=" + c +
    33.                 ", d=" + d +
    34.                 ", arrayOne=" + Arrays.toString(arrayOne) +
    35.                 '}';
    36.     }
    37. }
    复制代码

  • Step2: 在controller包下创建BookControllerThree类,代码如下:

    • Step2-1: 在该类中利用@Autowired自动依赖注入一个私有的Enterprise对象
      1. [/code] [align=center][img]https://i-blog.csdnimg.cn/direct/3177a5e18b4d450daeaeee6a67edaf42.png[/img][/align]
      2. [/list]
      3. [/list] [size=5]SpringBoot多情况开发设置[/size]
      4. [list]
      5. [*] SpringBoot提供多种情况设定(即:生产情况、开发情况、测试情况)如图所示,可资助开发者快速切换情况
      6. [align=center][img]https://i-blog.csdnimg.cn/direct/c931e862e3224dd188e69be3b1afbe36.png[/img][/align]
      7. [/list] [size=4]快速入门[/size]
      8.    本项目SpringBootDemoTwo已上传至Gitee,可自行下载。具体搭建步骤可详见SpringBoot快速入门,此处只举行关键步骤示例。该项目已上传至GItee,可自行下载
      9.   
      10. [list]
      11. [*]设置文件格式有三种,properties格式的设置文件举行多情况开发设置与另外两种不同,此处均会举行具体示例
      12. [/list] [size=3]yml及yaml格式的设置文件[/size]
      13. [list]
      14. [*] [b]Step1:[/b] 在源代码设置文件目录(即资源文件resources)下创建设置文件application.yml,代码如下:
      15.        --- 是 YAML 格式的多文档分隔符,用于区分不同情况的设置
      16.     [code]# 设置启动的情况---假设如今启用生产情况prospring:  profiles:    active: pro---# 生产情况server:
      17.   port: 81
      18. spring:  profiles: pro---# 开发情况server:
      19.   port: 82
      20. spring:  profiles: dev---# 测试情况server:  port: 83spring:  profiles: test
      复制代码

      • 留意:若SpringBoot版本过高则spring.profiles会被标志无效,且运行会报错,如图所示

      • 此时设置文件application.yml,代码更改如下
        1. # 设置启动的情况---假设如今启用生产情况prospring:  profiles:    active: pro---# 生产情况server:
        2.   port: 81
        3. spring:  config:    activate:      on-profile: pro---# 开发情况server:
        4.   port: 82
        5. spring:  config:    activate:      on-profile: dev---# 测试情况server:  port: 83spring:  config:    activate:      on-profile: test
        复制代码

    • Step2: 运行SpringBoot的引导类SpringBootDemoTwoApplication,截图如下

    properties格式的设置文件



    • Step1: 在源代码设置文件目录(即资源文件resources)下创建设置文件application-pro.properties,代码如下
      1. spring.application.name=SpringBootDemoTwo
      2. # 设置生产环境的端口号
      3. server.port=85
      复制代码
    • Step2: 在源代码设置文件目录(即资源文件resources)下创建设置文件application-dev.properties,代码如下
      1. spring.application.name=SpringBootDemoTwo
      2. # 设置开发环境的端口号
      3. server.port=86
      复制代码
    • Step3: 在源代码设置文件目录(即资源文件resources)下创建设置文件application-test.properties,代码如下
      1. spring.application.name=SpringBootDemoTwo
      2. # 设置测试环境的端口号
      3. server.port=87
      复制代码
    • Step4: 在源代码设置文件目录(即资源文件resources)下的设置文件application.properties中写入要启用的情况设置对应的设置文件名-后的内容,代码如下:
             以生产情况为例,由于生产情况对应的设置文件名为application-pro.properties,以是spring.profiles.active=pro
          若想启用别的情况,只需更改该设置文件spring.profiles.active的属性值即可
         
      1. spring.application.name=SpringBootDemoTwo
      2. # 设置启用的环境---此处以生产环境为例
      3. spring.profiles.active=pro
      复制代码
      运行SpringBoot的引导类SpringBootDemoTwoApplication,截图如下

    • 留意:

      • 若三种格式的设置文件均存在于项目中且设置内容均同等,则在以上三种设置文件示例中由于properties格式的设置文件优先级最高,以是生产情况、开发情况以及测试情况的端口号就会以properties格式的设置文件为准,也就是说这三种设置文件均存在且设置的内容一样时,properties格式的设置文件生效,而别的两种格式的设置文件失效,如上图所示

    多情况命令行启动参数设置



    • 留意
             本示例以SpringBoot多情况开发设置的快速入门为基准,由于该项目如今有多个设置文件,如图一所示,以是博主会将properties格式的三种情况设置文件备份放到bak文件夹下,以免影响后续操纵,如图二所示
          留意:此时application.properties会由于找不到三种情况设置文件导致多情况开发设置失效,转而使application.yml中对多情况开发的设置生效,如图三所示
         


    • 多情况命令行启动的指令格式

      • java -jar SpringBoot的jar包名.jar:启动对应的SpringBoot项目
      • java -jar SpringBoot的jar包名.jar --server.port=自定义的端口号:启动对应的SpringBoot项目并将端口号自定义为本身想用的端口号
      • java -jar SpringBoot的jar包名.jar --spring.profiles.active=想要切换的情况:启动对应的SpringBoot项目并切换情况(即生产、开发、测试)
      • java -jar SpringBoot的jar包名.jar --server.port=自定义的端口号 --spring.profiles.active=想要切换的情况:启动对应的SpringBoot项目并切换情况(即生产、开发、测试),同时将端口号自定义为本身想用的端口号

       后端开发人员在开发过程中的情况为开发情况,当后端人员开发完成后将SprootBoot项目打包成jar包发送给测试人员后,测试人员发现由于jar包中的情况为开发情况导致无法测试而且后端人员使用的端口号均与本身的辩论,则此时就用到了多情况命令行启动参数设置来将其改为测试情况并修改端口号
      多情况切换



    • Step1: 将该项执行Maven构建指令package来对SpringBoot项目SpringBootDemoTwo打包
             留意:在执行Maven构建指令package来对SpringBoot项目举行打包前,最好执行一下clean指令,以此来避免不必要的贫苦
         

    • Step2: 将jar包发给前端人员(此处在博主电脑上举行示例),然后在文件地点位置通过cmd打开命令窗口,输入指令java -jar SpringBoot的jar包名.jar 等运行成功后检察当前端口号,以此来判断是否是测试情况

      • 留意:若通过命令窗口报错:java.lang.UnsupportedClassVersionError: org/springframework/boot/loader/launch/JarLauncher has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0,说明你的jdk版本过低无法运行当前SpringBoot项目,则需要升级jdk版本,由于博主设置了jdk1.8和jdk21两个jdk版本,以是设置暂时情况变量的步骤如下:

        • Step2-1:将jdk版本暂时切换为jdk21:set JAVA_HOME1=F:\app\jdk-21,后为本身的jdk安装路径
        • Step2-2:使用set PATH=%JAVA_HOME1%\bin;%PATH%指令让暂时情况变量生效
        • Step2-3:输入指令java -jar SpringBoot的jar包名.jar 运行SpringBoot项目标jar包即可,如图所示,此时端口号为81,以是后端开发人员发送的jar包为开发情况



    • Step3: 在命令窗口界面ctrl+c停止项目运行,然后输入指令java -jar SpringBoot的jar包名.jar --server.port=自定义的端口号 --spring.profiles.active=想要切换的情况 ,如图所示

    • Step4: 再次运行后可看出已将jar包切换到测试情况,而且测试情况的端口号由原来的83变动为了100,如图所示

    Maven与SpringBoot的多情况开发兼容性题目

       题目引入:假设如今在Maven的pom.xml文件以及SpringBoot的设置文件中均设置了多情况开发,且Maven中以开发情况为主,SpringBoot以测试情况为主,则项目启动时是以哪个为主呢?
      

    • 由于命令行启动时是通过Maven的指令package将SpringBoot项目打包成一个jar包,然后通过命令窗口来启动,以是最终会以Maven的情况为主,以是在两者均设置了多情况时,会以Maven为主,SpringBoot为辅。
    快速入门

       本快速入门以多情况命令行启动参数设置的项目示例为基准,只举行关键步骤的演示
        标题:在Maven中设置多情况,然后通过SpringBoot的设置文件来获取当前启动的情况并在SpringBoot的设置文件中来设置对应的端口号
      

    • Step1: 在pom.xml文件中设置多情况,设置多情况代码如下:
      1. <!--定义多环境-->
      2. <profiles>
      3.     <!--定义具体的环境一:生产环境-->
      4.     <profile>
      5.         <id>pro</id>
      6.         <!--定义环境中专用的属性值-->
      7.         <properties>
      8.             <profile.active>pro</profile.active>
      9.         </properties>
      10.     </profile>
      11.     <!--定义具体的环境二:开发环境-->
      12.     <profile>
      13.         <id>dep</id>
      14.         <!--定义环境中专用的属性值-->
      15.         <properties>
      16.             <profile.active>dep</profile.active>
      17.         </properties>
      18.         <!--设置默认启动:即设置该环境为默认启动环境-->
      19.         <activation>
      20.             <activeByDefault>true</activeByDefault>
      21.         </activation>
      22.     </profile>
      23.     <!--定义具体的环境三:测试环境-->
      24.     <profile>
      25.         <id>test</id>
      26.         <!--定义环境中专用的属性值-->
      27.         <properties>
      28.             <profile.active>test</profile.active>
      29.         </properties>
      30.     </profile>
      31. </profiles>
      复制代码
    • Step2: 在pom.xml文件中添加以下插件,以此来开启SpringBoot设置文件目录加载属性的过滤器
      1. <!--开启SpringBoot配置文件目录加载属性的过滤器-->
      2. <plugin>
      3.     <groupId>org.apache.maven.plugins</groupId>
      4.     <artifactId>maven-resources-plugin</artifactId>
      5.     <version>3.3.1</version>
      6.     <configuration>
      7.         <encoding>UTF-8</encoding>
      8.         <useDefaultDelimiters>true</useDefaultDelimiters>
      9.     </configuration>
      10. </plugin>
      复制代码
      pom.xml文件完整代码如下
      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      4.     <modelVersion>4.0.0</modelVersion>
      5.     <parent>
      6.         <groupId>org.springframework.boot</groupId>
      7.         <artifactId>spring-boot-starter-parent</artifactId>
      8.         <version>3.4.0</version>
      9.         <relativePath/> <!-- lookup parent from repository -->
      10.     </parent>
      11.     <groupId>org.example</groupId>
      12.     <artifactId>SpringBootDemoTwo</artifactId>
      13.     <version>0.0.1-SNAPSHOT</version>
      14.     <name>SpringBootDemoTwo</name>
      15.     <description>SpringBootDemoTwo</description>
      16.     <url/>
      17.     <licenses>
      18.         <license/>
      19.     </licenses>
      20.     <developers>
      21.         <developer/>
      22.     </developers>
      23.     <scm>
      24.         <connection/>
      25.         <developerConnection/>
      26.         <tag/>
      27.         <url/>
      28.     </scm>
      29.     <properties>
      30.         <java.version>21</java.version>
      31.     </properties>
      32.     <dependencies>
      33.         <dependency>
      34.             <groupId>org.springframework.boot</groupId>
      35.             <artifactId>spring-boot-starter-web</artifactId>
      36.         </dependency>
      37.         <dependency>
      38.             <groupId>org.springframework.boot</groupId>
      39.             <artifactId>spring-boot-starter-test</artifactId>
      40.             <scope>test</scope>
      41.         </dependency>
      42.     </dependencies>
      43.     <!--定义多环境-->
      44.     <profiles>
      45.         <!--定义具体的环境一:生产环境-->
      46.         <profile>
      47.             <id>pro</id>
      48.             <!--定义环境中专用的属性值-->
      49.             <properties>
      50.                 <profile.active>pro</profile.active>
      51.             </properties>
      52.             <!--设置默认启动:即设置该环境为默认启动环境-->
      53.             <activation>
      54.                 <activeByDefault>true</activeByDefault>
      55.             </activation>
      56.         </profile>
      57.         <!--定义具体的环境二:开发环境-->
      58.         <profile>
      59.             <id>dep</id>
      60.             <!--定义环境中专用的属性值-->
      61.             <properties>
      62.                 <profile.active>dep</profile.active>
      63.             </properties>
      64.         </profile>
      65.         <!--定义具体的环境三:测试环境-->
      66.         <profile>
      67.             <id>test</id>
      68.             <!--定义环境中专用的属性值-->
      69.             <properties>
      70.                 <profile.active>test</profile.active>
      71.             </properties>
      72.         </profile>
      73.     </profiles>
      74.     <build>
      75.         <plugins>
      76.             <plugin>
      77.                 <groupId>org.springframework.boot</groupId>
      78.                 <artifactId>spring-boot-maven-plugin</artifactId>
      79.             </plugin>
      80.             <!--开启SpringBoot配置文件目录加载属性的过滤器-->
      81.             <plugin>
      82.                 <groupId>org.apache.maven.plugins</groupId>
      83.                 <artifactId>maven-resources-plugin</artifactId>
      84.                 <version>3.3.1</version>
      85.                 <configuration>
      86.                     <encoding>UTF-8</encoding>
      87.                     <useDefaultDelimiters>true</useDefaultDelimiters>
      88.                 </configuration>
      89.             </plugin>
      90.         </plugins>
      91.     </build>
      92. </project>
      复制代码
    • Step3: 在SpringBoot的设置文件中引用属性,代码如下
      1. # 设置启动的情况---读取pom.xml文件中要启用的情况spring:  profiles:    active: ${profile.active}---# 生产情况server:
      2.   port: 81
      3. spring:  config:    activate:      on-profile: pro---# 开发情况server:
      4.   port: 82
      5. spring:  config:    activate:      on-profile: dev---# 测试情况server:  port: 83spring:  config:    activate:      on-profile: test
      复制代码
      执行Maven的package指令打包后,检察jar包中的application.yml文件可知,SpringBoot已成功获取到Maven的多情况设置

    设置文件分类

       题目引入:
      ​ 后端人员将SpringBoot项目打包发给前端或测试人员时,由于与前端或测试人员的设置辩论,以是前端或测试人员需要重新设置暂时属性,这就有了一个题目:
      ​ 若需要设置的暂时属性就一两个则很轻松就能设置完;但如果需要设置的暂时属性过多,此时前端或测试人员编写对应的指令就会过多,如许就很贫苦,如图所示。因此SpringBoot就引入了多级设置文件来解决该题目
      



    • SpringBoot中4级设置文件

      • 1级: file :config/application.yml 【最高】
      • 2级: file :application.yml
      • 3级:classpath:config/application.yml
      • 4级:classpath:application.yml 【最低】
      • 1级优先级最高,4级优先级最低

    • 解释

      • 1级、2级为打包后,在jar包地点目录下按1级2级规定格式设置
      • 3级、4级为后端开发人员在项目标类路径下按3级4级规定格式设置
      • 具体解释可见示例部门内容

    • 作用:

      • 1级与2级留做体系 打包后 设置通用属性
      • 3级与4级用于体系 开发阶段 设置通用属性

    快速入门



    • 本快速入门的项目SpringBootDemoThree已上传至Gitee,可自行下载。搭建过程可详见SpringBoot快速入门,此处只举行关键步骤演示
    • 本快速入门通过端口号的变化来演示,如许更能直观看出4级设置文件的优先级次序
    • 本项目以yml格式的设置文件为基准举行演示,以是会删除原有的application.properties文件
    4级设置文件示例



    • Step1: 在源代码设置文件目录(即资源文件resources)下创建application.yml设置文件,代码及项目运行截图如下
             在设置文件中将该项目标端口号设置为80
         

    • 留意:

      • 由于此时该设置文件是直接在源代码设置文件目录(即资源文件resources)下的,以是会被自动认定为4级设置文件

    3级设置文件示例



    • Step1: 在源代码设置文件目录(即资源文件resources)下创建config目录,然后在config目录下创建application.yml设置文件,代码及项目运行截图如下

    • 留意

      • 虽然如今有两个名称同等的设置文件,而且有一个在config目录下,但是项目在启动过程中若辨认到在源代码设置文件目录(即资源文件resources)下存在config目录,就会自动将该目录下的设置文件视为3级设置文件。此时,处于config目录下的设置文件生效,而直接处于源代码设置文件目录(即资源文件resources)下的设置文件会失效

    2级设置文件示例

       在举行2级、3级设置文件示例之前需要将项目打包,此处博主已举行打包
      

    • Step1: 打开jar包地点目录,在该目录下创建设置文件application.yml,代码及项目运行截图如下

    • 留意

      • 与jar包同级的设置文件即为2级设置文件,它会覆盖原来的3级和4级设置文件

    1级设置文件示例



    • Step1: 打开jar包地点目录,在该目录下创建config目录,并在config目录下设置文件application.yml,代码及项目运行截图如下

    • 留意

      • 虽然如今有两个名称同等的设置文件,而且有一个在config目录下,但是jar包在启动过程中若辨认到同级目录下存在config目录,就会自动将该目录下的设置文件视为1级设置文件。此时,处于config目录下的设置文件生效,而处于与jar包同级的设置文件会失效

    SpringBoot整合JUnit

       本项目SbJunitDemo以SpringBoot已上传至Gitee,可自行下载。搭建过程可详见SpringBoot快速入门,此处只举行关键步骤演示
      情况准备



    • Step1: 创建业务层service包

      • Step1-1: 在该包下创建BookService接口,代码如下
        1. package at.guigu.service;
        2. import java.awt.print.Book;
        3. public interface BookService {
        4.     public void save();
        5. }
        复制代码
      • Step1-2: 在service包下创建impl包,并在impl包下创建BookService接口的实现类BookServiceImpl,代码如下
        1. package at.guigu.service.impl;
        2. import at.guigu.service.BookService;
        3. import org.springframework.stereotype.Service;
        4. @Service
        5. public class BookServiceImpl implements BookService {
        6.     @Override
        7.     public void save() {
        8.         System.out.println("BookService Running...");
        9.     }
        10. }
        复制代码

    测试示例



    • Step1: 在该项目自动生成的测试类SbJunitDemoApplicationTests中编写代码,如下
      1. package at.guigu;
      2. import at.guigu.service.BookService;
      3. import org.junit.jupiter.api.Test;
      4. import org.springframework.beans.factory.annotation.Autowired;
      5. import org.springframework.boot.test.context.SpringBootTest;
      6. @SpringBootTest
      7. class SbJunitDemoApplicationTests {
      8.     @Autowired
      9.     private BookService bookService;
      10.     @Test
      11.     void contextLoads() {
      12.         bookService.save();
      13.     }
      14. }
      复制代码
      运行后截图如下

    • 留意

      • 在现实测试过程中我们除了可以使用项目所提供的测试类的方法void contextLoads()外,还可以使用自定义的测试方法,如下所示

      • 在现实测试过程中我们除了可以使用项目所提供的测试类SbJunitDemoApplicationTests之外,也可自定义测试类,此处不在演示,可详见Spring整合Junit部门内容
      • 若测试类在SpringBoot启动类的包或子包中,则可以省略启动类(即引导类)的设置(即省略@SpringBootTest注解的classes属性的设置);反之则不可以省略

    可能出现的题目

       测试类必须在SpringBoot引导类的包或子包中,否则会失效,报错: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
      解决办法:给@SpringBootTest注解添加classes属性且属性值为SpringBoot引导类
      

    • Step1: 在项目默认的测试类地点包的上一层包下创建test包,并在test包下创建ServiceTest测试类

      • Step1-1: 给ServiceTest测试类加上@SpringBootTest
      • Step1-2: 利用@Autowired举行自动依赖注入
      • Step1-3: 编写测试方法并用@Test注解修饰
      1. package at.test;
      2. import at.guigu.test.BookService;
      3. import org.junit.jupiter.api.Test;
      4. import org.springframework.beans.factory.annotation.Autowired;
      5. import org.springframework.boot.test.context.SpringBootTest;
      6. @SpringBootTest
      7. public class ServiceTest {
      8.     @Autowired
      9.     private BookService bookService;
      10.     @Test
      11.     public void serviceTest() {
      12.         bookService.save();
      13.         System.out.println("运行自定义的测试方法");
      14.     }
      15. }
      复制代码
      运行后报错如下:


    • Step2: 给ServiceTest测试类的@SpringBootTest注解指定SpringBoot引导类,代码如下
      1. package at.test;
      2. import at.guigu.SbJunitDemoApplication;
      3. import at.guigu.test.BookService;
      4. import org.junit.jupiter.api.Test;
      5. import org.springframework.beans.factory.annotation.Autowired;
      6. import org.springframework.boot.test.context.SpringBootTest;
      7. @SpringBootTest(classes = SbJunitDemoApplication.class)
      8. public class ServiceTest {
      9.     @Autowired
      10.     private BookService bookService;
      11.     @Test
      12.     public void serviceTest() {
      13.         bookService.save();
      14.         System.out.println("运行自定义的测试方法");
      15.     }
      16. }
      复制代码
      运行截图如下

    SpringBoot整合MyBatis

       本项目SbMyBatisDemo已上传至Gitee,可自行下载
      项目创建



    • Step1:

    • Step2: 若创建的是Web项目标话则按下图步骤创建即可;反之则清除10、11两步即可

    • Step3: 添加MyBatis的起步依赖:MyBatis Framework以及MySQL Driver

      初始项目布局如下

    情况准备



    • Step1: 创建数据库表tb_brand 并使IDEA与数据库建立连接 ,SQL代码如下
      1. DROP TABLE IF EXISTS tb_brand;
      2. -- 创建品牌表brand
      3. CREATE TABLE IF NOT EXISTS tb_brand
      4. (
      5.         -- id 主键
      6.         id int PRIMARY KEY auto_increment,
      7.         -- 品牌名称
      8.         brand_name VARCHAR(20),
      9.         -- 企业名称
      10.         company_name VARCHAR(20),
      11.         -- 排序字段
      12.         ordered INT,
      13.         -- 描述信息
      14.         description VARCHAR(100),
      15.         -- 状态:0:禁用  1:启用
      16.         status INT
      17. );
      18. -- 添加数据
      19. INSERT INTO tb_brand(brand_name, company_name, ordered, description, status)
      20. VALUES ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
      21.                          ('华为', '华为技术有限公司', 100, '华为致力于构建万物互联的世界', 1),
      22.        ('小米', '小米科技有限公司', 50, 'Are you OK', 1);
      23. SELECT * FROM tb_brand;
      复制代码
    • Step2: 在pom.xml文件中添加数据源坐标依赖
             留意:若不添加,则会使用SpringBoot的默认数据源。此处根据现实情况来决定是否添加数据源。博主使用druid数据源
          此处只给出相关的两个数据源坐标,可自行选择使用
         
      1. <!--druid坐标-->
      2. <dependency>
      3.     <groupId>com.alibaba</groupId>
      4.     <artifactId>druid</artifactId>
      5.     <version>1.2.18</version>
      6. </dependency>
      7. <!--c3p0坐标-->
      8. <dependency>
      9.     <groupId>com.mchange</groupId>
      10.     <artifactId>c3p0</artifactId>
      11.     <version>0.9.5.5</version>
      12. </dependency>
      复制代码
    • Step3: 将设置文件application.properties改为application.yml格式的设置文件,并在该设置文件中设置数据库连接信息以及数据源信息
             留意:若使用的是cp30则type属性值即为cp30信息。博主使用的为Druid数据源
         
      1. # 配置数据库连接信息以及数据源信息
      2. spring:
      3.   datasource:
      4.     type: com.alibaba.druid.pool.DruidDataSource
      5.     driver-class-name: com.mysql.cj.jdbc.Driver
      6.     url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
      7.     username: root
      8.     password: 123456
      复制代码
    • Step4: 创建一个与三层架构包同级的pojo包,并在该包下创建实体类Brand,代码如下
      1. package at.guigu.pojo;
      2. import org.apache.ibatis.type.Alias;
      3. @Alias("brand")
      4. public class Brand {
      5.     // id 主键
      6.     private Integer id;
      7.     // 品牌名称
      8.     private String brandName;
      9.     // 企业名称
      10.     private String companyName;
      11.     // 排序字段 用于将某个品牌显示在最前面让消费者看到
      12.     private Integer ordered;
      13.     // 描述信息
      14.     private String description;
      15.     // 状态:0:禁用  1:启用
      16.     private Integer status;
      17.     public Brand() {}
      18.     public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
      19.         this.id = id;
      20.         this.brandName = brandName;
      21.         this.companyName = companyName;
      22.         this.ordered = ordered;
      23.         this.description = description;
      24.         this.status = status;
      25.     }
      26.     public Integer getId() {
      27.         return id;
      28.     }
      29.     public void setId(Integer id) {
      30.         this.id = id;
      31.     }
      32.     public String getBrandName() {
      33.         return brandName;
      34.     }
      35.     public void setBrandName(String brandName) {
      36.         this.brandName = brandName;
      37.     }
      38.     public String getCompanyName() {
      39.         return companyName;
      40.     }
      41.     public void setCompanyName(String companyName) {
      42.         this.companyName = companyName;
      43.     }
      44.     public Integer getOrdered() {
      45.         return ordered;
      46.     }
      47.     public void setOrdered(Integer ordered) {
      48.         this.ordered = ordered;
      49.     }
      50.     public String getDescription() {
      51.         return description;
      52.     }
      53.     public void setDescription(String description) {
      54.         this.description = description;
      55.     }
      56.     public Integer getStatus() {
      57.         return status;
      58.     }
      59.     public void setStatus(Integer status) {
      60.         this.status = status;
      61.     }
      62.     @Override
      63.     public String toString() {
      64.         return "Brand{" +
      65.                 "id=" + id +
      66.                 ", brandName='" + brandName + '\'' +
      67.                 ", companyName='" + companyName + '\'' +
      68.                 ", ordered=" + ordered +
      69.                 ", description='" + description + '\'' +
      70.                 ", status=" + status +
      71.                 '}';
      72.     }
      73. }
      复制代码
    • Step5: 创建三层架构包,且初始代码分别如下

      • 在持久层dao包下创建BrandDao接口
        1. package at.guigu.dao;
        2. import org.apache.ibatis.annotations.Mapper;
        3. @Mapper
        4. public interface BrandDao {
        5. }
        复制代码
      • 在该SpringBoot项目标源代码设置文件目录(即main包下的resources目录下)创建多级目录,然后在与BrandDao接口对应的目录下创建 SQL映射文件BrandDao.xml ,如图所示,SQL映射文件初始代码如下所示
        1. <?xml version="1.0" encoding="UTF-8" ?>
        2. <!DOCTYPE mapper
        3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        5. <!--namespace:名称空间-->
        6. <mapper namespace="at.guigu.dao.BrandDao">
        7.     <!--结果映射-->
        8.     <resultMap id="brandResultMap" type="brand">
        9.         <!--由于id为主键,且数据库中的字段名和对应结果映射的目标类中的属性名一样,所以此处不需要主键映射,只需进行非主键映射即可-->
        10.         <result column="brand_name" property="brandName"/>
        11.         <result column="company_name" property="companyName"/>
        12.     </resultMap>
        13. </mapper>
        复制代码

        • 留意:结果映射中的type="brand"会标红报错,以是解决办法为:利用@Alias("别名")注解为类的全类名设置类型别名

      • 在业务层service包下创建BrandService接口及其实现类,初始代码如下:
        1. package at.guigu.service;
        2. public interface BrandService {
        3.    
        4. }
        复制代码
        1. package at.guigu.service.impl;
        2. import at.guigu.dao.BrandDao;
        3. import at.guigu.service.BrandService;
        4. import org.springframework.beans.factory.annotation.Autowired;
        5. import org.springframework.stereotype.Service;
        6. @Service
        7. public class BrandServiceImpl implements BrandService {
        8.     @Autowired
        9.     private BrandDao brandDao;
        10. }
        复制代码
      • 在表现层controller包下创建BrandController类,初始代码如下:
        1. package at.guigu.controller;
        2. import org.springframework.web.bind.annotation.RequestMapping;
        3. import org.springframework.web.bind.annotation.RestController;
        4. // @RestController = @Controller+ @ResponseBody
        5. @RestController
        6. // Restful风格
        7. @RequestMapping(value = "/brands")
        8. public class BrandController {
        9. }
        复制代码

    查询全部数据

       SpringBoot注解开发形式仅以查询全部数据示例,别的增编削操纵可根据MyBatis完整知识点汇总示例操纵
      

    • Step1: 在dao包下的BrandDao接口中写入查询方法,然后在对应的SQL映射文件中写入对应SQL语句
             留意:
          ​ 简单查询SQL语句接纳注解方式,复杂SQL语句接纳映射文件方式
          ​ 在java文件中利用注解形式誊写SQL语句时,不需要对特别字符举行转义

      • BrandDao接口代码如下
        1. package at.guigu.dao;
        2. import at.guigu.pojo.Brand;
        3. import org.apache.ibatis.annotations.Mapper;
        4. import org.apache.ibatis.annotations.Param;
        5. import org.apache.ibatis.annotations.Select;
        6. import java.util.List;
        7. import java.util.Map;
        8. @Mapper
        9. public interface BrandDao {
        10.     // 查询所有条数据
        11.     @Select("select * from tb_brand")
        12.     List<Brand> all();
        13.     // 查询单条数据
        14.     @Select("select * from tb_brand where id = #{id}")
        15.     Brand selectById(@Param("id") Integer id);
        16.     //静态单条件查询
        17.     @Select("select * from tb_brand where id > #{id}")
        18.     List<Brand> selectBySingleConOne(Integer id);
        19.     // 动态单条件查询——对象参数接收
        20.     List<Brand> selectBySingleConTwo(Brand brand);
        21.     // 动态单条件查询——Map集合参数接收
        22.     List<Brand> selectBySingleConTwoo(Map map);
        23.     // 动态多条件查询——对象参数接收
        24.     List<Brand> selectByMaxConOne(Brand brand);
        25.     // 动态多条件查询——Map集合参数接收
        26.     List<Brand> selectByMaxConTwo(Map map);
        27. }
        复制代码
      • SQL映射文件BrandDao.xml代码如下
        1. <?xml version="1.0" encoding="UTF-8" ?>
        2. <!DOCTYPE mapper
        3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        5. <!--namespace:名称空间-->
        6. <mapper namespace="at.guigu.dao.BrandDao">
        7.     <!--结果映射-->
        8.     <resultMap id="brandResultMap" type="brand">
        9.         <!--由于id为主键,且数据库中的字段名和对应结果映射的目标类中的属性名一样,所以此处不需要主键映射,只需进行非主键映射即可-->
        10.         <result column="brand_name" property="brandName"/>
        11.         <result column="company_name" property="companyName"/>
        12.     </resultMap>
        13.     <!--动态单条件查询——对象参数接收-->
        14.     <select id="selectBySingleConTwo" resultMap="brandResultMap">
        15.         select * from tb_brand
        16.         <where>
        17.             <choose> <!--类似于switch-->
        18.                 <when test="status != null">
        19.                     status = #{status}
        20.                 </when>
        21.                 <when test="companyName != null and companyName != ''">
        22.                     company_name like #{companyName}
        23.                 </when>
        24.                 <when test="brandName != null and brandName != ''">
        25.                     brand_name like #{brandName}
        26.                 </when>
        27.             </choose>
        28.         </where>
        29.     </select>
        30.     <!--动态单条件查询——Map集合参数接收-->
        31.     <select id="selectBySingleConTwoo" resultMap="brandResultMap">
        32.         select * from tb_brand
        33.         <where>
        34.             <choose> <!--类似于switch-->
        35.                 <when test="status != null">
        36.                     status = #{status}
        37.                 </when>
        38.                 <when test="companyName != null and companyName != ''">
        39.                     company_name like #{companyName}
        40.                 </when>
        41.                 <when test="brandName != null and brandName != ''">
        42.                     brand_name like #{brandName}
        43.                 </when>
        44.             </choose>
        45.         </where>
        46.     </select>
        47.     <!--动态多条件查询——对象参数接收-->
        48.     <select id="selectByMaxConOne" resultMap="brandResultMap">
        49.         select * from tb_brand
        50.         <where>
        51.             <if test="status != null">
        52.                 and status = #{status}
        53.             </if>
        54.             <if test="companyName != null and companyName != ''">
        55.                 and company_name like #{companyName}
        56.             </if>
        57.             <if test="brandName != null and brandName != ''">
        58.                 and brand_name like #{brandName}
        59.             </if>
        60.         </where>
        61.     </select>
        62.     <!--动态多条件查询——Map集合参数接收-->
        63.     <select id="selectByMaxConTwo" resultMap="brandResultMap">
        64.         select * from tb_brand
        65.         <where>
        66.             <if test="status != null">
        67.                 and status = #{status}
        68.             </if>
        69.             <if test="companyName != null and companyName != ''">
        70.                 and company_name like #{companyName}
        71.             </if>
        72.             <if test="brandName != null and brandName != ''">
        73.                 and brand_name like #{brandName}
        74.             </if>
        75.         </where>
        76.     </select>
        77. </mapper>
        复制代码

    • Step2: 誊写业务层service包下的代码,代码如下

      • 在业务层service包下的BrandService接口来调用dao包下的BrandDao接口中的方法,代码如下
        1. package at.guigu.service;
        2. import at.guigu.pojo.Brand;
        3. import java.util.List;
        4. import java.util.Map;
        5. public interface BrandService {
        6.     // 查询所有条数据
        7.     public List<Brand> getAll();
        8.     // 查询单条数据
        9.     public Brand getById(Integer id);
        10.     //静态单条件查询
        11.     public List<Brand> selectBySingleConOne(Integer id);
        12.     // 动态单条件查询——对象参数接收
        13.     public List<Brand> selectBySingleConTwo(Brand brand);
        14.     // 动态单条件查询——Map集合参数接收
        15.     public List<Brand> selectBySingleConTwoo(Map map);
        16.     // 动态多条件查询——对象参数接收
        17.     public List<Brand> selectByMaxConOne(Brand brand);
        18.     // 动态多条件查询——Map集合参数接收
        19.     public List<Brand> selectByMaxConTwo(Map map);
        20. }
        复制代码
      • BrandService接口的实现类BrandServiceImpl代码如下
        1. package at.guigu.service.impl;
        2. import at.guigu.dao.BrandDao;
        3. import at.guigu.pojo.Brand;
        4. import at.guigu.service.BrandService;
        5. import org.springframework.beans.factory.annotation.Autowired;
        6. import org.springframework.stereotype.Service;
        7. import java.util.List;
        8. import java.util.Map;
        9. @Service
        10. public class BrandServiceImpl implements BrandService {
        11.     @Autowired
        12.     private BrandDao brandDao;
        13.     @Override
        14.     public List<Brand> getAll() {
        15.         return brandDao.all();
        16.     }
        17.     @Override
        18.     public Brand getById(Integer id) {
        19.         return brandDao.selectById(id);
        20.     }
        21.     @Override
        22.     public List<Brand> selectBySingleConOne(Integer id) {
        23.         return brandDao.selectBySingleConOne(id);
        24.     }
        25.     @Override
        26.     public List<Brand> selectBySingleConTwo(Brand brand) {
        27.         return brandDao.selectBySingleConTwo(brand);
        28.     }
        29.     @Override
        30.     public List<Brand> selectBySingleConTwoo(Map map) {
        31.         return brandDao.selectBySingleConTwoo(map);
        32.     }
        33.     @Override
        34.     public List<Brand> selectByMaxConOne(Brand brand) {
        35.         return brandDao.selectByMaxConOne(brand);
        36.     }
        37.     @Override
        38.     public List<Brand> selectByMaxConTwo(Map map) {
        39.         return brandDao.selectByMaxConTwo(map);
        40.     }
        41. }
        复制代码

    • Step3: 在表现层controller包下的BrandController类的代码如下:
      1. package at.guigu.controller;
      2. import at.guigu.pojo.Brand;
      3. import at.guigu.service.BrandService;
      4. import org.springframework.beans.factory.annotation.Autowired;
      5. import org.springframework.web.bind.annotation.*;
      6. import java.util.List;
      7. import java.util.Map;
      8. // @RestController = @Controller+ @ResponseBody
      9. @RestController
      10. // Restful风格
      11. @RequestMapping(value = "/brands")
      12. public class BrandController {
      13.     @Autowired
      14.     private BrandService brandService;
      15.     // 查询所有数据
      16.     @GetMapping
      17.     public List<Brand> getAll() {
      18.         return brandService.getAll();
      19.     }
      20.     // 查询单条数据:通过id查询
      21.     @GetMapping("/{id}")
      22.     public Brand getById(@PathVariable(value = "id") Integer id) {
      23.         return brandService.getById(id);
      24.     }
      25.     // 静态单条件查询
      26.     @GetMapping("/singleConOne/{id}")
      27.     public List<Brand> selectBySingleConOne(@PathVariable(value = "id") Integer id) {
      28.         return brandService.selectBySingleConOne(id);
      29.     }
      30.     // 动态单条件查询——对象参数接收
      31.     @GetMapping("/singleConTwo")
      32.     public List<Brand> selectBySingleConTwo(@RequestParam("brandName") String brandName, @RequestParam("companyName") String companyName,
      33.                                             @RequestParam("ordered") Integer ordered,@RequestParam("description") String description,
      34.                                             @RequestParam("status") Integer status) {
      35.         Brand brand = new Brand();
      36.         brand.setBrandName(brandName);
      37.         brand.setCompanyName(companyName);
      38.         brand.setOrdered(ordered);
      39.         brand.setDescription(description);
      40.         brand.setStatus(status);
      41.         return brandService.selectBySingleConTwo(brand);
      42.     }
      43.     // 动态单条件查询——Map集合参数接收
      44.     @GetMapping("/singleConTwoo")
      45.     public List<Brand> selectBySingleConTwoo(@RequestParam("map") Map map) {
      46.         return brandService.selectBySingleConTwoo(map);
      47.     }
      48.     // 动态多条件查询——对象参数接收
      49.     @GetMapping("/maxConOne")
      50.     public List<Brand> selectByMaxConOne(@RequestParam("brandName") String brandName, @RequestParam("companyName") String companyName,
      51.                                          @RequestParam("ordered") Integer ordered,@RequestParam("description") String description,
      52.                                          @RequestParam("status") Integer status) {
      53.         Brand brand = new Brand();
      54.         brand.setBrandName(brandName);
      55.         brand.setCompanyName(companyName);
      56.         brand.setOrdered(ordered);
      57.         brand.setDescription(description);
      58.         brand.setStatus(status);
      59.         return brandService.selectByMaxConOne(brand);
      60.     }
      61.     // 动态多条件查询——Map集合参数接收
      62.     @GetMapping("/maxConTwo")
      63.     public List<Brand> selectByMaxConTwo(@RequestParam("map") Map map) {
      64.         return brandService.selectByMaxConTwo(map);
      65.     }
      66. }
      复制代码
      运行后截图如下:

    可能出现的题目

       经过以上步骤之后运行项目,可能会报如下图所示错误,原因是实体种别名设置未生效
      



    • 解决方法为:在SpringBoot的设置文件application.yml中指定 MyBatis 别名扫描路径。此时,设置文件的代码如下:
      1. # 配置数据库连接信息以及数据源信息
      2. spring:
      3.   datasource:
      4.     type: com.alibaba.druid.pool.DruidDataSource
      5.     driver-class-name: com.mysql.cj.jdbc.Driver
      6.     url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
      7.     username: root
      8.     password: 123456
      9. # 指定 MyBatis 别名扫描路径mybatis:  type-aliases-package: at.guigu.pojo
      复制代码
    SpringBoot整合SSM框架

       本项目SbSsmDemo已上传至Gitee,可自行下载
      本项目已ssm整合为基准,重复步骤均省略,可详见博客
      项目创建



    • Step1:

    • Step2: 若创建的是Web项目标话则按下图步骤创建即可;反之则清除10、11两步即可

    • Step3: 添加MyBatis的起步依赖:MyBatis Framework以及MySQL Driver

      初始项目布局如下

    情况准备



    • Step1: 创建数据库ssm_db,然后在该数据库下创建表tbl_book 并使IDEA与数据库建立连接 ,SQL代码如下
      1. -- 创建ssm_db数据库
      2. CREATE DATABASE IF NOT EXISTS ssm_db CHARACTER SET utf8;
      3. -- 使用ssm_db数据库
      4. USE ssm_db;
      5. -- 创建tbl_book表
      6. CREATE TABLE tbl_book(
      7.     id INT PRIMARY KEY AUTO_INCREMENT, -- 图书编号
      8.     TYPE VARCHAR(100), -- 图书类型
      9.     NAME VARCHAR(100), -- 图书名称
      10.     description VARCHAR(100) -- 图书描述
      11. );
      12. -- 添加初始化数据
      13. INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring实战 第5版','Spring入门经典教材,深入理解Spring原理技术内幕');
      14. INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5核心原理与30个类手写实战','十年沉淀之作,手写Spring精华思想');
      15. INSERT INTO tbl_book VALUES(NULL,'计算机理论','Spring 5设计模式','深入Spring源码剖析,Spring源码蕴含的10大设计模式');
      16. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播就该这么做:主播高效沟通实战指南','李子柒、李佳琦、薇娅成长为网红的秘密都在书中');
      17. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍');
      18. INSERT INTO tbl_book VALUES(NULL,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');
      复制代码
    • Step2: 在pom.xml文件中添加数据源坐标依赖
             留意:若不添加,则会使用SpringBoot的默认数据源。此处根据现实情况来决定是否添加数据源。博主使用druid数据源
          此处只给出相关的两个数据源坐标,可自行选择使用
         
      1. <!--druid坐标-->
      2. <dependency>
      3.     <groupId>com.alibaba</groupId>
      4.     <artifactId>druid</artifactId>
      5.     <version>1.2.18</version>
      6. </dependency>
      7. <!--c3p0坐标-->
      8. <dependency>
      9.     <groupId>com.mchange</groupId>
      10.     <artifactId>c3p0</artifactId>
      11.     <version>0.9.5.5</version>
      12. </dependency>
      复制代码
    • Step3: 将设置文件application.properties改为application.yml格式的设置文件,并在该设置文件中设置数据库连接信息以及数据源信息
             留意:若使用的是cp30则type属性值即为cp30信息。博主使用的为Druid数据源
         
      1. # 配置端口号
      2. server:
      3.   port: 80
      4.   
      5. # 配置数据库连接信息以及数据源信息
      6. spring:
      7.   datasource:
      8.     type: com.alibaba.druid.pool.DruidDataSource
      9.     driver-class-name: com.mysql.cj.jdbc.Driver
      10.     url: jdbc:mysql://localhost:3306/ssm_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
      11.     username: root
      12.     password: 123456
      13. # 指定 MyBatis 别名扫描路径
      14. mybatis:
      15.   type-aliases-package: at.guigu.pojo
      复制代码
    别的步骤



    • Step1: 将ssm整合项目RestfulDemo中的三层架构包、pojo包、exception包、resolver包及包中的代码,以及SQL映射文件复制到该SpringBoot整合SSM框架的项目SbSsmDemo中,如图所示

    • Step2: 将静态资源以及html页面复制均到源代码设置文件目录(即资源文件resources)下的static目录下,如图所示

    接口测试

    使用JUint来测试业务层接口



    • Step1: 在测试目录test下创建测试类及对应的包,代码及步骤如图所示

      运行结果如下

    使用POstMan测试表现层

    运行引导类后,运行截图如下


    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

饭宝

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表