springboot复习(黑马)

学习目标


基于SpringBoot框架的程序开发步骤

熟练使用SpringBoot配置信息修改服务器配置

基于SpringBoot的完成SSM整合项目开发

一、SpringBoot简介


1. 入门案例

问题导入

SpringMVC的HelloWord程序大家还记得吗?

  • SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程

  • 原生开发SpringMVC程序过程

1.1 入门案例开发步骤

环境准备

①:创建新模块,选择Spring初始化,并配置模块相关基础信息
②:选择当前模块需要使用的技术集
③:开发控制器类
@RestController
public class Controller01 {

    @RequestMapping("/sayHi")
    public String sayHi(){
        System.out.println("hi...");
        return "hi ... springboot...";
    }
}

④:运行自动生成的Application类

访问页面

重新启动

最简SpringBoot程序所包含的基础文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.itheima</groupId>
    <artifactId>demo1_helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1_helloworld</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>
package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/*/*
    @SpringBootApplication:
        1. 表示这个类是一个springboot应用程序的入口类。
        2. 要想让程序启动,只需要在main方法里面写上这样的一句话:
              SpringApplication.run(当前类的字节码对象, args);
        3. 拓展:
            3.1 springboot项目启动的时候,默认会扫描启动类所在的位置,以及它后续的所有子包。
            3.2 查找到类里面打的注解 @Controller , @Service , @RequestMapping.
            3.3 springApplication.run 传递进去当前类的字节码对象,也是可以确定当前
                这个启动器它的包是哪个!
 */
@SpringBootApplication
public class Demo1HelloworldApplication {

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

}

Spring程序与SpringBoot程序对比

注意事项:

基于idea开发SpringBoot程序需要确保联网且能够加载到程序框架结构

1.2 基于SpringBoot官网创建项目

保存到桌面

解压完之后 用idea打开他

因为用到了Mysql 所以得配置数据库

已经启动

1.3 SpringBoot项目快速启动

① 对SpringBoot项目打包(执行Maven构建指令package)

② 执行启动指令

java -jar ava -jar demo1_helloworld-0.0.1-SNAPSHOT.jar    # 项目的名称根据实际情况修改

例子

注意事项:

jar支持命令行启动需要依赖maven插件支持,请确认打包时是否具有SpringBoot对应的maven插件。

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

如果没有这个依赖maven插件 打包就只有4k左右

这个时候跟本运行不了

2. SpringBoot概述

问题导入

学习了SpringBoot入门案例之后,感觉对比SpringMVC哪一个更加方便简洁?

  • SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程

  • Spring程序缺点

  • 配置繁琐

  • 依赖设置繁琐

  • SpringBoot程序优点

  • 自动配置

  • 起步依赖(简化依赖配置)

  • 辅助功能(内置服务器,……)

28行到225行 <properties></properties>

226行 到2737行 <dependencyManagement> </dependencyManagement>

2.1 起步依赖

  • starter

  • SpringBoot中常见项目名称,定义了当前项目使用的所有项目坐标,以达到减少依赖配置的目的

  • 可以认为这个起步依赖相当于一个开关 我们主要用了这个东西 就相当用了他的全套功能

   <!--starter:
            1. 在springboot的依赖里面很常见
            2. 一般会称之为起步依赖
            3. 所谓起步依赖就是说: 只要导入这个起步依赖,起步依赖的背后会包含着一大堆依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

parent

  • 所有SpringBoot项目要继承的项目,定义了若干个坐标版本号(依赖管理,而非依赖),以达到减少依赖冲突的目的

  • spring-boot-starter-parent(2.5.0)与 spring-boot-starter-parent(2.4.6)共计57处坐标版本不同

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--继承 springboot 父亲-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--项目本身的信息-->
    <groupId>com.itheima</groupId>
    <artifactId>demo1_helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1_helloworld</name>
    <description>Demo project for Spring Boot</description>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.5.0</version>
    </parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <packaging>pom</packaging>    
    ...
</project>

实际开发

  • 使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供

  • 如发生坐标错误,再指定version(要小心版本冲突)

如我们要用到Mysql

     <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

当然也不是什么都有管理

比如druid就不被管理

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

如果不写版本号的话 就会出现unknown 这个时候 我们就知道在springboot的父亲的父亲里面并没有管理这个依赖 这个时候 我们就能自己添加版本号

自己添加版本号

2.2 辅助功能

  • SpringBoot程序启动

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/*/*
    @SpringBootApplication:
        1. 表示这个类是一个springboot应用程序的入口类。
        2. 要想让程序启动,只需要在main方法里面写上这样的一句话:
              SpringApplication.run(当前类的字节码对象, args);
        3. 拓展:
            3.1 springboot项目启动的时候,默认会扫描启动类所在的位置,以及它后续的所有子包。
            3.2 查找到类里面打的注解 @Controller , @Service , @RequestMapping.
            3.3 springApplication.run 传递进去当前类的字节码对象,也是可以确定当前
                这个启动器它的包是哪个!
 */
@SpringBootApplication
public class Demo1HelloworldApplication {

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

}
  • SpringBoot在创建项目时,采用jar的打包方式

  • SpringBoot的引导类是项目的入口,运行main方法就可以启动项目

  • 使用maven依赖管理变更起步依赖项

  • Jetty比Tomcat更轻量级,可扩展性更强(相较于Tomcat),谷歌应用引擎(GAE)已经全面切换为Jetty

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--排除tomcat,不用tomcat-->
            <!--<exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>-->
        </dependency>
        <!--添加进来jetty-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--整合Junit-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

全部pom.xml

`<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--继承 springboot 父亲-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!--项目本身的信息-->
    <groupId>com.itheima</groupId>
    <artifactId>demo1_helloworld</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo1_helloworld</name>
    <description>Demo project for Spring Boot</description>
    <!--默认使用JDK 1.8的语法来编译代码-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <!--添加依赖-->
    <!--starter:
            1. 在springboot的依赖里面很常见
            2. 一般会称之为起步依赖
            3. 所谓起步依赖就是说: 只要导入这个起步依赖,起步依赖的背后会包含着一大堆依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--排除tomcat,不用tomcat-->
            <!--<exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>-->
        </dependency>

        <!--添加进来jetty-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>






        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>



        <!--整合Junit-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <!--这是用来配置打jar包的, 有了这个插件的配置,那么项目打出来的jar包,就具备了执行的入口。
        就可以使用 java -jar xxxx.jar 启动起来项目-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、基础配置

环境准备 demo2_properties

前面的创建操作和demo1类似 不在展示


1. 配置文件格式

问题导入

框架常见的配置文件有哪几种形式?

1.1 修改服务器端口

SpringBoot提供了多种属性配置方式

  • application.properties

server.port=8081

重启

小备注:如果发现启动报错

解决办法

查看进程 看看有没的被人家使用了

发现被14452使用了

打开任务管理器

找到14452

在重新启动就可以

application.yml

server:
  port: 8082

重新启动

application.yaml

server:
  port: 8083

发现不提示 解决办法 1.2 自动提示功能消失解决方案

解决完小叶子问题之 后 就会有提示了

重启

1.2 自动提示功能消失解决方案

操作步骤:

第一种:

如果发现上面的ok点不了 可能是没有application.properties 我们要先把这个给创建出来

第二种

1.3 SpringBoot配置文件加载顺序(了解)

  • application.properties > application.yml > application.yaml

注意事项:

  1. SpringBoot核心配置文件名为application

  1. SpringBoot内置属性过多,且所有属性集中在一起修改,在使用时,通过提示键+关键字修改属性

2. yaml

问题导入

什么是yaml,和properties有什么区别?

  • YAML(YAML Ain't Markup Language),一种数据序列化格式

  • 优点:

  • 容易阅读

  • 容易与脚本语言交互

  • 以数据为核心,重数据轻格式

  • YAML文件扩展名

  • .yml(主流)

  • .yaml

2.1 yaml语法规则

  • 大小写敏感

  • 属性层级关系使用多行描述,每行结尾使用冒号结束

  • 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)

  • 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔)

  • #表示注释

  • 核心规则:数据前面要加空格与冒号隔开

2.2 yaml数组数据

  • 数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔

数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔

2.3 yaml数据读取

  • 2.3.1 使用@Value读取单个数据,属性名引用方式:${一级属性名.二级属性名……}
package com.itheima.web;

/*
    在这个类里面,使用@Value来读取yml文件中的数据。
 */

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller01 {
    @Value("${lesson}")
    private String lesson;

    //@Value("${第一层.第二层.第三层.属性名}")
    @Value("${server.port}")
    private String port;

    @Value("${enterprise.name}")
    private String name;

    @Value("${enterprise.subject[0]}")
    private String subject;

    @RequestMapping("/readYml")
    public String readYml(){

        System.out.println("lesson = " + lesson);
        System.out.println("port = " + port);
        System.out.println("name = " + name);
        System.out.println("subject = " + subject);

        return "hi springboot...";
    }
}
lesson: SpringBoot

server:
  port: 8082

enterprise:
  name: 传智播客
  age: 16
  tel: 4006184000
  subject:
    - Java
    - 前端
    - 大数据

注:如果报错的话 修改一下编码

如果还报错的话 就clean一下

如果还是报错的话

如果还是报错 我们就把前面没有用到的application.properties和application.yaml的端口号给注释了或把这二个文件删除

端口号给注释了

或删除

  • 2.3.2 封装全部数据到Environment对象
package com.itheima.web;

/*
    在这个类里面,使用Environment来读取yml文件中的数据。
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller02 {

    @Autowired
    private Environment env;

    @RequestMapping("/readYml02")
    public String readYml(){

        System.out.println("lesson = " + env.getProperty("lesson"));
        System.out.println("port = " + env.getProperty("server.port"));
        System.out.println("name = " + env.getProperty("enterprise.name"));
        System.out.println("subject = " + env.getProperty("enterprise.subject[0]"));

        return "hi springboot.0222..";
    }
}
lesson: SpringBoot

server:
  port: 8082

enterprise:
  name: 传智播客
  age: 16
  tel: 4006184000
  subject:
    - Java
    - 前端
    - 大数据
  • 2.3.3 自定义对象封装指定数据【常用】==

因为封装 要得到属性 用到@Data注解 所以要加入以下依赖

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

package com.itheima.bean;

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

@Data
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
    private String name;
    private int age ;
    private String tel;
    private String [] subject;
}
package com.itheima.web;

/*
    在这个类里面,使用Environment来读取yml文件中的数据。
 */

import com.itheima.bean.Enterprise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RestController
public class Controller03 {

    @Autowired
    private Enterprise enterprise;

    @RequestMapping("/readYml03")
    public String readYml(){

        System.out.println("enterprise = " + enterprise);


        return "hi springboot.0333..";
    }
}
lesson: SpringBoot

server:
  port: 8082

enterprise:
  name: 传智播客
  age: 16
  tel: 4006184000
  subject:
    - Java
    - 前端
    - 大数据

自定义对象封装数据警告解决方案

问题:

解决

加入依赖

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

3. 多环境开发配置

环境准备

问题导入

在实际开发中,项目的开发环境、测试环境、生产环境的配置信息是否会一致?如何快速切换?

3.1 多环境启动配置

  • yaml文件多环境启动

3.1.1 在YML文件多环境启动
# 激活具体的环境
spring:
  profiles:
    active: dev

---
# 定义开发环境
server:
  port: 80

spring:
  config:
    activate:
      on-profile: dev
---

# 定义生产环境
server:
  port: 81

spring:
  config:
    activate:
      on-profile: prod

---
# 定义测试环境
server:
  port: 82
spring:
  config:
    activate:
      on-profile: test

3.1.2 properties文件多环境启动

application.properties

# 使用properties的文件格式来定义多环境
# 1. 一套环境就一个properties文件,命名格式: application-环境的id.properries
# 2. 在application.properties 里面激活具体的环境。
spring.profiles.active=dev

application-dev.properties

server.port=8081

application-prod.properties

server.port=8082

application-test.properties

server.port=8083

启动

3.2 多环境启动命令格式

把application.properties放到properties-bak

  • 带参数启动SpringBoot

打包

重新cmd 修改端口

参数加载优先顺序

  • 参看文档:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

3.3 多环境开发控制

Maven与SpringBoot多环境兼容(步骤)

环境准备

①:Maven中设置多环境属性
<profiles>
        <!--maven里面的开发环境配置-->
        <profile>
            <id>dev_mvn</id>
            <properties>
                <a>dev</a>
            </properties>

            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>

        <!--maven里面的生产环境配置-->
        <profile>
            <id>prod_mvn</id>
            <properties>
                <a>prod</a>
            </properties>
        </profile>

        <!--maven里面的测试环境配置-->
        <profile>
            <id>test_mvn</id>
            <properties>
                <a>test</a>
            </properties>
        </profile>
    </profiles>
②:SpringBoot中引用Maven属性
# 激活具体的环境
spring:
  profiles:
    active: ${a} # 这里的值是动态变化的,由maven来控制它的变化

---
# 声明开发环境
server:
  port: 80
spring:
  config:
    activate:
      on-profile: dev
---
# 声明生产环境
server:
  port: 81
spring:
  config:
    activate:
      on-profile: prod
---
# 声明测试环境
server:
  port: 82
spring:
  config:
    activate:
      on-profile: test

③:执行Maven编译指令

  • Maven指令执行完毕后,生成了对应的包,其中类参与编译,但是配置文件并没有编译,而是复制到包中

解决思路:对于源码中非java类的操作要求加载Maven对应的属性,解析${}占位符

④:对资源文件开启对默认占位符的解析
    <!--这个插件是用来解析资源文件里面的 ${}-->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>utf-8</encoding>
                    <useDefaultDelimiters>true</useDefaultDelimiters>
                </configuration>
            </plugin>

重新编译

Maven编译加载到属性,编译顺利通过

如果想要换其他的环境

也可以用命令的方式

打包

4. 配置文件分类

问题导入

SpringBoot的配置文件可以放在项目的哪些地方?

java –jar springboot.jar --spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima --server.tomcat.connection-timeout=-1 ... ...
  • SpringBoot中4级配置文件

1级: file :config/application.yml 【最高】

2级: file :application.yml

3级:classpath:config/application.yml

4级:classpath:application.yml 【最低】

  • 作用:

1级与2级留做系统打包后设置通用属性

3级与4级用于系统开发阶段设置通用属性

  • 演示3级和4级

优先使用8888端口 因为config/application.yml的优先级高于application.yml 【最低】

  • 演示第二级

  • 演示第一级

Ctrl+C 结束前面的

重新启动

三、整合第三方技术


1. 整合JUnit

环境准备

有web

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

无web

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

不导入web也是可以自动扫描包 也是可以自动创建工程

问题导入

回忆一下Spring整合JUnit的步骤?

1.1 Spring整合JUnit(复习)

1.2 SpringBoot整合JUnit

先跑一下自己写的测试类

@SpringBootTest
public class MyTest {


    @Test
    public void test01(){
        System.out.println("test01....");

    }
}

MyTest里面测试service的方法

测试类

package com.itheima;
import com.itheima.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyTest {
    @Autowired
    private UserService us;

    @Test
    public void test01(){

        System.out.println("test01....");
        us.add();

    }
}

接口

package com.itheima.service;

public interface UserService {
    void add();
}

实现类

package com.itheima.service.impl;

import com.itheima.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        System.out.println("调用了UserServiceImpl的add方法~!!~");
    }
}

@SpringBootTest解释

@SpringBootTest(classes = Demo5JunitApplication.class)

什么时候加classes

1. 如果测试类所在的包 是 位于 启动类所在的包或者它的子包里面, 或者大家的包名一致,那么可以省略启动类不写!

启动类: com.itheima

测试: com.itheima

2. 如果测试类所在的包,并不是位于启动类所在包的下面,那么一定要指定启动类是谁, 否则有可能出错!

比如我们把test包放到com下面 不写classes就会出错

如果写上classes

2. 基于SpringBoot实现SSM整合

问题导入

回忆一下Spring整合MyBatis的核心思想?

2.1 Spring整合MyBatis(复习)

2.1 Spring整合MyBatis(复习)

  • SpringConfig

  • 导入JdbcConfig

  • 导入MyBatisConfig

`@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, MyBatisConfig.class})
public class SpringConfig {

}

JDBCConfig

  • 定义数据源(加载properties配置项:driver、url、username、password)

#jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=itheima
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource getDataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}

MyBatisConfig

  • 定义SqlSessionFactoryBean

  • 定义映射配置

@Bean
public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource) {
    SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
    ssfb.setTypeAliasesPackage("com.itheima.domain");
    ssfb.setDataSource(dataSource);
    return ssfb;
}
@Bean
public MapperScannerConfigurer getMapperScannerConfigurer() {
    MapperScannerConfigurer msc = new MapperScannerConfigurer();
    msc.setBasePackage("com.itheima.dao");
    return msc;
}

2.2 SpringBoot整合MyBatis

  • SpringBoot整合Spring(不存在)

  • SpringBoot整合SpringMVC(不存在)

  • SpringBoot整合MyBatis(主要)

①:创建新模块,选择Spring初始化,并配置模块相关基础信息
②:选择当前模块需要使用的技术集(MyBatis、MySQL)
③:设置数据源参数
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_test
    username: root
    password: 123456

注意事项:

  1. SpringBoot版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区,或在MySQL数据库端配置时区解决此问题

jdbc:mysql://localhost:3306/springboot_test?serverTimezone=UTC

加入druid连接池 和lombok依赖

   <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
④:定义数据层接口与映射配置

实体类bean

package com.itheima.bean;

import lombok.Data;

@Data
public class Book {
    private int id;
    private String type;
    private String name;
    private String description;
}
⑤:测试类中注入dao接口,测试功能
package com.itheima.dao;

import com.itheima.bean.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/*
    要想创建出来dao的代理对象,那么需要告诉springboot,这个dao在哪里?
        1. 第一种做法: 就是直接在dao的接口上打上注解 @Mapper

        2. 第二种做法: 在启动类上打上注解: @MapperScan("com.itheima.dao")
 */
@Mapper
public interface BookDao {

    @Select("select * from tbl_book")
    List<Book> findAll();
}

package com.itheima;

import com.itheima.dao.BookDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Demo6MybatisApplicationTests {

    @Autowired
    private BookDao dao;

    @Test
    void testFindAll() {
        System.out.println("dao.findAll() = " + dao.findAll());
    }
}

测试结果:

如果不用druid连接池 就用光连接池

spring:
  datasource:
    #type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_test
    username: root
    password: 123456
/*
    要想创建出来dao的代理对象,那么需要告诉springboot,这个dao在哪里?
        1. 第一种做法: 就是直接在dao的接口上打上注解 @Mapper

        2. 第二种做法: 在启动类上打上注解: @MapperScan("com.itheima.dao")
 */

第二种做法

package com.itheima;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.itheima.dao")
@SpringBootApplication
public class Demo6MybatisApplication {

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

}

如果二种都不打 会报以下错误

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itheima.dao.BookDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

2.3 案例-SpringBoot实现ssm整合

① 环境准备
② 导入静态页面
③ yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_test
    username: root
    password: 123456

启动

访问

http://localhost:8080/pages/books.html
④ 前端
         methods: {
                //列表
                getAll() {

                    axios.get("/books").then(resp=>{
                        console.log(resp);
                        //this.dataList = resp.data.data;

                    });
⑤ bean实体类
`package com.itheima.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/*
    这个类是用来包装返回给前端的数据
 */

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Result {
    private int code; //代表这次请求的代号: 表示成功或者表示失败
    private String msg; //代表这次请求的代号的一个简短说明: 添加品牌成功 或者  添加品牌失败
    private Object data; //代表这次请求要返回给客户端的数据,一般是针对查询操作。
}
⑥ dao接口
package com.itheima.dao;

import com.itheima.bean.Book;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface BookDao {

    @Select("select * from tbl_book")
    List<Book>  findAll();
}
⑦ service接口
`package com.itheima.service;

import com.itheima.bean.Book;

import java.util.List;

public interface BookService {
    List<Book> findAll();
}
⑧ BookServiceImpl实现类
`package com.itheima.service.impl;

import com.itheima.bean.Book;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao dao;

    @Override
    public List<Book> findAll() {
        return dao.findAll();
    }
}
⑨ web 【Controller】
`package com.itheima.web;

import com.itheima.bean.Book;
import com.itheima.bean.Result;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/books")
@RestController
public class BookController {

    @Autowired
    private BookService bs;

    @GetMapping
    public Result findAll(){
        List<Book> list = bs.findAll();
        return new Result(1, "查询成功" , list);
    }
}

启动类打上@MapperScan("com.itheima.dao")

package com.itheima;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.itheima.dao")
@SpringBootApplication
public class Demo7SsmApplication {

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

}

启动

⑩ 前端
 methods: {
                //列表
                getAll() {

                    axios.get("/books").then(resp=>{
                        console.log(resp);
                        this.dataList = resp.data.data;

                    });

重启

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/912.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

GPT-4技术报告

摘要 链接&#xff1a;https://cdn.openai.com/papers/gpt-4.pdf 我们汇报了GPT-4的发展&#xff0c;这是一个大规模的多模态模型&#xff0c;可以接受图像和文本输入并产生文本输出。虽然在许多现实场景中&#xff0c;GPT-4的能力不如人类&#xff0c;但它在各种专业和学术基…

数智链接,新一代校园招聘解决方案

疫情3年市场巨变&#xff0c;00后新生代初登上求职舞台&#xff0c;中和作用下&#xff0c;牛客发现新生代求职发生明显变化&#xff0c;企业校招也要随之而变&#xff0c;并率先提出以种草、精准、专业为特点的新一代校园招聘解决方案。01.学生求职变了&#xff01;安全感、非…

奇异值分解(SVD)原理与在降维中的应用

奇异值分解(SVD)原理与在降维中的应用 奇异值分解(Singular Value Decomposition&#xff0c;以下简称SVD)是在机器学习领域广泛应用的算法&#xff0c;它不光可以用于降维算法中的特征分解&#xff0c;还可以用于推荐系统&#xff0c;以及自然语言处理等领域。是很多机器学习算…

GPT-4来袭:开启人工智能新时代

文章目录介绍GPT4 模型演示示例示例 1示例 2示例 3示例 4示例 5最后Reference介绍 2023年3月15日&#xff0c;OpenAI公司正式发布了先进的自然语言处理模型GPT-4&#xff0c;前不久发布的GPT-3.5模型只能理解文字的语言模型&#xff0c;而新发布的GPT4则是多模态模型&#xff…

【java】了解常见集合类

了解常见集合类 一、集合类框架 1、集合类框架结构图 首先我们要对集合类结构有一个大体的认识&#xff0c;所有集合都继承于迭代器&#xff0c;分为单列集合和映射集合&#xff0c;单列集合分为有序可重复和有序不可重复&#xff0c;大概结构如下图所示 2、主要集合类的介…

你真的知道如何系统高效地学习数据结构与算法吗?

文章目录前言&#xff1a;什么是数据结构&#xff1f;什么是算法&#xff1f;学习这个算法需要什么基础&#xff1f;学习的重点在什么地方&#xff1f;一些可以让你事半功倍的学习技巧1.边学边练&#xff0c;适度刷题2.多问、多思考、多互动3.打怪升级学习法4.知识需要沉淀&…

文心一言---中国版的“ChatGPT”狂飙的机会或许要出现了

⭐️我叫忆_恒心&#xff0c;一名喜欢书写博客的在读研究生&#x1f468;‍&#x1f393;。 如果觉得本文能帮到您&#xff0c;麻烦点个赞&#x1f44d;呗&#xff01; 近期会不断在专栏里进行更新讲解博客~~~ 有什么问题的小伙伴 欢迎留言提问欧&#xff0c;喜欢的小伙伴给个三…

linux 基础

1.Shell 命令的格式如下&#xff1a;command -options [argument]command: Shell 命令名称。options&#xff1a; 选项&#xff0c;同一种命令可能有不同的选项&#xff0c;不同的选项其实现的功能不同。argument&#xff1a; Shell 命令是可以带参数的&#xff0c;也可以不带参…

【计算机二级Python】综合题目

计算机二级python真题 文章目录计算机二级python真题一、简单应用——明星投票二、综合应用题《评奖学金 两问》一、简单应用——明星投票 描述使用字典和列表型变量完成最有人气的明星的投票数据分析。投票信息由附件里的文件vote.txt给出,一行只有一个明星姓名的投票才是有效…

【BLE 5.3无线MCU CH582】1、初识CH582开发板(开箱)

1、认识板子 优点&#xff1a; &#xff08;1&#xff09;引脚全部引出&#xff1b; &#xff08;2&#xff09;USB下载程序&#xff1b; &#xff08;3&#xff09;TYPE-C接口好评&#xff1b; &#xff08;4&#xff09;板载连个两个USB口&#xff0c;都可以供电&#xff1b;…

前端性能优化之HTTP缓存

前端缓存 前端缓存可分为两大类&#xff1a;HTTP 缓存和浏览器缓存。 我们今天重点是 HTTP 缓存&#xff0c;下面这张图是前端缓存的一个大致知识点&#xff1a; HTTP 缓存 首先解决困扰绕人们的老大难问题&#xff1a; 一、什么是HTTP缓存&#xff1f; HTTP 缓存会存储与请…

六个实用技巧让你轻松写出优雅的链表代码

文章目录&#x1f4d5;前言&#xff1a;如何轻松写出正确的链表代码&#xff1f;&#x1f4d6;技巧一&#xff1a;理解指针或引用的含义&#x1f4d6;技巧二&#xff1a;警惕指针丢失和内存泄漏&#x1f4d6;技巧三&#xff1a;利用哨兵简化实现难度&#x1f4d6;技巧四&#x…

HTTP 协议

文章目录1. 前言2. HTTP 协议3. fiddler 的安装与认识4. HTTP 协议报文格式4.1 请求4.2 响应5. 构造 HTTP 请求5.1 基于 form 表单构造 HTTP 请求5.2 基于 ajax 构造 HTTP 请求6. postman7. HTTPS7.1 加密7.2 HTTPS 的工作过程1. 前言 前面几篇文章 &#xff0c; 说了关于 前端…

C++继承[万字详解]

目录 一.继承的介绍 1.1、继承的概念 1.2、继承的定义 1.2.1、定义格式 1.2.2、继承关系和访问限定符 1.2.3、继承基类成员后&#xff0c;在子类中成员访问方式的变化 二.基类和派生类对象赋值转化 三.继承中的作用域 四.派生类的默认成员函数 ★派生类的构造函数 派…

有关pytorch的一些总结

Tensor 含义 张量&#xff08;Tensor&#xff09;&#xff1a;是一个多维数组&#xff0c;它是标量、向量、矩阵的高维拓展。 创建 非随机创建 1.用数组创建 将数组转化为tensor np.ones([a,b]) 全为1 #首先导入PyTorch import torch#数组创建 import numpy as np anp.arr…

4.类的基本概念

目录 4.1 类的概述 类是一种活动的数据结构 4.2 程序和类&#xff1a;一个快速实例 4.3 声明类 ​4.4 类成员 4.4.1 字段 1.显示和隐式字段初始化 2. 声明多个字段 4.4.2 方法 4.5 创建变量和类的实例 4.6 为数据分配内存 合并这两个步骤 4.7 实例成员 4.8 访问修饰…

2023年天津市逆向re3.exe解析(超详细)

2023年天津市逆向re3.exe解析 1.拖进IDA里进行分析2.动态调试(过程省略了)3.解密加密算法4.输入FLAG 回显成功!1.拖进IDA里进行分析 打开后是这么一个程序,直接找到main函数f5反编译即可,这里要注意程序第一次反编译出的代码会有点问题,需要点进引用的那些其他sub函数里面…

【面试题】闭包是什么?this 到底指向谁?

一通百通&#xff0c;其实函数执行上下文、作用域链、闭包、this、箭头函数是相互关联的&#xff0c;他们的特性并不是孤立的&#xff0c;而是相通的。因为内部函数可以访问外层函数的变量&#xff0c;所以才有了闭包的现象。箭头函数内没有 this 和 arguments&#xff0c;所以…

百度将?百度已!

仿佛一夜之间&#xff0c;创业公司OpenAI旗下的ChatGPT就火遍全球。这是一场十分罕见的科技盛宴。下到普通用户&#xff0c;上到各科技大厂都在讨论ChatGPT的前景&#xff0c;国外的微软、谷歌&#xff0c;国内的百度、腾讯、阿里等等都在布局相关业务。比尔盖茨更是称ChatGPT与…

OSPF*MGRE实验:

OSPF*MGRE 一&#xff1a;实验拓扑 实验目的&#xff1a; IP地址配置如拓扑所示&#xff1b; 路由器配置&#xff1a; ospf-10 [r1]ospf 10 [r1-ospf-10]area 0 [r1-ospf-10-area-0.0.0.0]network 192.168.1.1 0.0.0.0 [r2]ospf 10 [r2-ospf-10]area 10 [r2-ospf-10-area-0.0.…
最新文章