资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

一篇文章带你掌握主流办公框架——SpringBoot

一篇文章带你掌握主流办公框架——SpringBoot

在之前的文章中我们已经学习了SSM的全部内容以及相关整合

创新互联公司一直秉承“诚信做人,踏实做事”的原则,不欺瞒客户,是我们最起码的底线! 以服务为基础,以质量求生存,以技术求发展,成交一个客户多一个朋友!为您提供成都网站设计、成都做网站、成都网页设计、重庆小程序开发、成都网站开发、成都网站制作、成都软件开发、成都APP应用开发是成都本地专业的网站建设和网站设计公司,等你一起来见证!

SSM是Spring的产品,主要用来简化开发,但我们现在所介绍的这款框架——SpringBoot,却是用来简化Spring开发的框架

SpringBoot是由Pivowtal团队提供的全新框架,其设计目的就是用来简化Spring应用的初始搭建以及开发过程,用来简化开发工具的工具,你是否已经满怀期待~

温馨提醒:在学习前请学习SSM内容以及Maven的高阶内容(依赖传递)等内容

SpringBoot简介

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

SpringBoot概述

SpringBoot是针对Spring的繁琐过程进行优化而产生的框架

Spring程序缺点:

  • 配置繁琐
  • 依赖设置繁琐

SpringBoot程序优点:

  • 自动配置
  • 起步依赖(简化依赖配置)
  • 辅助功能(内置服务器等)

SpringBoot项目开发

我们通过一个简单的SpringBoot案例和SSM案例的比较来展现SpringBoot的优势

SSM框架构造

首先我们回忆一下SSM框架的基本构造图:

我们来总结一些SSM框架必备的一些文档:

  1. pom.xml配置文档
  2. ServletConfig配置Java类
  3. SpringMvcConfig配置Java类
  4. Collector服务层Java文档

SpringBoot框架构造

相对而言,我们的SpringBoot将SSM的框架内容隐藏起来,达到简化框架的作用

我们下面来介绍创建一个SpringBoot框架的具体步骤:

  1. IDEA创建新项目,选择SpringBoot框架,JDK选择1.8版本(Default默认在网页下载,需要联网)
  1. 选择Maven,Java,jar等相关选项,注意选择Java8(目前SpringBoot只支持Java8的版本)
  1. 选择Web中的SpringWeb,确保右侧存在Spring Web选项(上方可选择SpringBoot版本)
  1. 创建项目即可
  1. 删除无关项目,只保留src和pom.xml即可
  1. 我们仅需书写一个Collector相关类即可
package com.itheima.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("id ==> "+id);
        return "hello , spring boot!";
    }

}
  1. 点击启动Application.java文件即可(由系统自动创建)
package com.itheima;

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

@SpringBootApplication
public class Application {

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

}

以上至此,我们的SpringBoot项目就开发完毕了

除此之外,我们的SpringBoot的核心内容实际上存在于pom.xml中,我们会在下述内容中进行介绍



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.0
    

    com.itheima
    springboot_01_quickstart
    0.0.1-SNAPSHOT

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


我们会发现需要我们书写代码的部分仅仅只有Collector这一部分,相比于SSM框架简化了并非一点点

SSM框架与SpringBoot框架比较

我们将SSM框架与SpringBoot框架进行简单的对比:

类/配置文件 Spring SpringBoot
pom文件中的坐标 手工添加 勾选添加
web3.0配置类 手工添加
Spring/SpringMvc配置类 手工添加
控制器 手工添加 手工添加

我们可以明显比较出两者的显著差距!

注意:基于IDEA开发的SpringBoot框架需要联网到SpringBoot官网加载程序框架结构

非IDEA进行SpringBoot开发

我们在实际工作中,可能使用的开发工具并非只有IDEA

那么IDEA中存在有SpringBoot的开发架构,其他不包含SpringBoot开发架构选项的软件就无法开发了吗?

我们可以选择到官网进行jar包下载直接导入开发即可:

  1. 打开官网(官网地址:Spring Boot)
  1. 拉至页面底部,找到快速开发标志,点击进入创建界面
  1. 勾选相对应图标,点击创建即可
  1. 创建后会自动下载jar包,直接导入所用软件即可

SpringBoot快速启动

我们在实际开发中,常常会做到前后端分离开发

那么我们的SpringBoot中所使用的服务器或开发软件等是否还需要交付给前端呢

SpringBoot为我们提供了一种全新的服务器开启方法,我们只需要将SpringBoot打包后交付给前端,前端就可直接进行开启

  1. 项目打包
  1. 打包后在当前页面采用cmd命令行输入以下指令即可直接开启服务器(注意需要在该jar包的文件夹目录下)
java -jar SpringBoot文件包名.jar(可tab键补全)

注意点:

  1. 我们需要将所需的数据库信息交付给前端,因为SpringBoot只负责项目的开启,与数据库无关

  2. 该方法是由一种pom.xml中的插件支持的,请确保存在该插件(SpringBoot自动创建)

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

SpringBoot起步依赖

在简单介绍SpringBoot的项目开发之后,你是否有疑惑为什么SpringBoot能够省略如此多的信息来直接开发

其实这一切都是源于SpringBoot的依赖的直接创建,我们称之为起步依赖:

  • parent起步依赖继承
  • starter起步依赖继承

我们给出部分pom.xml配置文件内部进行分析:



    4.0.0
    
    
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.0
    

    com.itheima
    springboot_01_quickstart
    0.0.1-SNAPSHOT

    
    
        1.8
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


总而言之,SpringBoot创建时自带的一系列起步依赖帮助我们简化了大量SSM的繁琐操作

我们再来详细介绍几个词语:

Starter:

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

Parent:

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

实际开发:

  • 使用任意坐标时,仅书写GAV中的G和A,不需要书写V
  • 如若发生坐标错误,再指定Version(小心版本冲突)

SpringBoot程序启动

SpringBoot程序启动方法就是开启Application.java文件即可

package com.itheima;

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

@SpringBootApplication
public class Application {

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

}

我们给出两个注意点:

  • SpringBoot在创建项目时,采用jar的打包方式
  • SpringBoot的引导类是项目的入口,运行main方法就可以启动项目

SpringBoot切换服务器

我们最后给出一个Maven使用技巧来切换服务器

SpringBoot中默认使用Tomcat服务器并安装了对应插件,

那么我们如果想切换服务器,只需要排除掉Tomcat插件,并添加新的插件即可



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.0
    

    com.itheima
    springboot_01_quickstart
    0.0.1-SNAPSHOT

    
        1.8
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    org.springframework.boot
                    spring-boot-starter-tomcat
                
            
        

        
        
            org.springframework.boot
            spring-boot-starter-jetty
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


SpringBoot基础配置

我们在Spring中能够实现的技术,在SpringBoot中同样可以实现

接下来我们依次来介绍一些SpringBoot基本配置的方法和多环境开发的问题

SpringBoot配置格式

SpringBoot为我们提供了三种配置格式来管理SpringBoot的配置(注意:以下配置均存在于resources文件夹中):

  1. application.properties
# 修改服务器端口号为80
server.port=80
  1. application.yml (主流)
# 修改服务器端口号为81(注意:存在空格)
server:
 port: 81
  1. application.yaml
# 修改服务器端口号为82(注意:存在空格)
server:
 port: 82

当三者均存在时,其优先级为:application.properties>application.yml >application.yaml

以上三种配置格式均在resources文件夹下创建相对应名称以及后缀的文件下书写:

注意:

application.properties属于SpringBoot自带,不需要创建

application.yml,application.yaml需要自我创建,因而不被标记为配置文件

如果我们希望该文件被标记为配置文件并包含有补全功能,我们需要手动设置为配置文件

yaml文件详细介绍

我们在这里详细介绍一下yaml文件:

  • YAML,一种数据序列化格式

优点:

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

YAML文件扩展名:

  • .yml(主流)
  • .yaml

YAML语法规则:

  • 大小写敏感

  • 属性层级关系

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

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

  • # 表示注释

  • 使用 - 来表示数据开始符号(数组)

YAML语法使用规范示例:

server:
  port: 82

logging:
  level:
    root: info

likes:
  - music
  - game
  - PE

YAML的数据读取方法:

首先我们先给出我们在yml文件中所列出的属性:

lesson: SpringBoot

server:
  port: 80

enterprise:
  name: itcast
  age: 16
  tel: 
  subject:
    - Java
    - 前端
    - 大数据

下面我们来介绍yaml数据读取的三种方法:

  1. ${属性名},${属性名.属性名},${属性名.属性名[数组下标]}
package com.itheima.controller;

import com.itheima.domain.Enterprise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/books")
public class BookController {
    //使用@Value读取单一属性数据
    @Value("${lesson}")
    private String lesson;
    @Value("${server.port}")
    private Integer port;
    @Value("${enterprise.subject[0]}")
    private String subject_00;
    
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(lesson);
        System.out.println(port);
        System.out.println(subject_00);
        return "hello , spring boot!";
    }

}
  1. Environment对象匹配方法
package com.itheima.controller;

import com.itheima.domain.Enterprise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    //使用Environment封装全配置数据(自动装配封装Environment,里面会包含yaml中所有属性和属性值)
    @Autowired
    private Environment environment;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        // 我们采用environment的getProperty方法,根据属性名,获得属性值
        System.out.println(environment.getProperty("lesson"));
        System.out.println(environment.getProperty("server.port"));
        System.out.println(environment.getProperty("enterprise.age"));
        System.out.println(environment.getProperty("enterprise.subject[1]"));
        return "hello , spring boot!";
    }

}
  1. 自定义对象封装指定数据
// 自定义对象Enterprise实现类(属于Domain)

package com.itheima.domain;

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

import java.util.Arrays;

//封装yaml对象格式数据必须先声明当前实体类受Spring管控
@Component
//使用@ConfigurationProperties注解定义当前实体类读取配置属性信息,通过prefix属性设置读取哪个数据
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
    private String name;
    private Integer age;
    private String tel;
    private String[] subject;

    @Override
    public String toString() {
        return "Enterprise{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", tel='" + tel + '\'' +
                ", subject=" + Arrays.toString(subject) +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String[] getSubject() {
        return subject;
    }

    public void setSubject(String[] subject) {
        this.subject = subject;
    }
}
// 服务层Controller

package com.itheima.controller;

import com.itheima.domain.Enterprise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    // 自动装配实现类即可
    @Autowired
    private Enterprise enterprise;


    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(enterprise);
        return "hello , spring boot!";
    }

}


        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

SpringBoot多环境启动

我们在开发过程中可能会采用不同的环境,频繁的转换环境当然不是一个好办法

SpringBoot选择配置多环境来控制环境选择启动

我们从两种不同的配置文件方向来讲解多环境:

  1. yaml多环境启动:
# yaml采用 --- 来表示环境层级更换 

# yaml采用 spring:profiles:active: 环境id 设置启用的环境
spring:
  profiles:
    active: dev

---
#开发环境
#yaml采用 spring:config:activate:on-profile: 环境id 来定义当前环境id(规范写法)
spring:
  config:
    activate:
      on-profile: dev
#以下属于环境配置
server:
  port: 80
---
#生产
#yaml采用 spring:profiles: 环境id 来定义当前环境id(旧版写法,同样适用)
spring:
  profiles: pro
#以下属于环境配置  
server:
  port: 81
---
#测试
#yaml采用 spring:profiles: 环境id 来定义当前环境id(旧版写法,同样适用)
spring:
  profiles: test
#以下属于环境配置  
server:
  port: 82
---
  1. properties多环境启动:
# application.properties文件(环境主文件)

#设置启用的环境
spring.profiles.active=pro
# application-dev.properties文件(环境配置文件)

# 设置相关资源配置
server.port=8080
# application-pro.properties文件(环境配置文件)

# 设置相关资源配置
server.port=8081
# application-test.properties文件(环境配置文件)

# 设置相关资源配置
server.port=8082

SpringBoot前端多环境启动

我们前面提及过SpringBoot的快速启动直接将jar包打包后发给前端就可以采用命令行启动服务器

但是我们的配置可能会导致更多的细节问题:

  1. 当我们的yaml出现中文注释时,需要将IDEA的encoding均设置为UTF-8
  1. 当我们的前端需要不同的环境配置时,我们不能在后台手动设置默认环境,因而需要采用指令设置
前端在调用时,可以采用指令来更改默认环境

默认开启服务器
java -jar jar包名称.jar

更换默认条件开启服务器样板
java -jar jar包名称.jar --配置属性=配置值

更换默认环境开启服务器
java -jar jar包名称.jar --spring.profiles.active=test

更换默认端口号开启服务器
java -jar jar包名称.jar --server.port=88

更换条件可以叠加使用
java -jar jar包名称.jar --spring.profiles.active=test --server.port=88

SpringBoot多环境兼容问题

SpringBoot中存在有很多的环境设置,不仅如此,包括有Maven也存在有多环境配置

那么Maven的多环境配置优先级和SpringBoot的多环境配置优先级谁的更高呢?

  • 我们的package操作是由Maven来完成的
  • 多环境优先级:Maven > SpringBoot

我们通过一个简单的案例来证明:

  1. Maven中配置多环境属性


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.0
    
    com.itheima
    springboot_05_maven_and_boot_profile
    0.0.1-SNAPSHOT
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.apache.maven.plugins
                maven-resources-plugin
                3.2.0
                
                    UTF-8
                    true
                
            
        
    

    
    
        
        
            dev
            
            
                dev
            
        
        
        
            pro
            
            
                pro
            
            
            
                true
            
        
        
        
            test
            
            
                test
            
        
    


  1. SpringBoot配置文件中引入Maven属性
# 设置启用的环境
# 采用${}引用Maven中的属性
spring:
  profiles:
    active: ${profile.active}

---
#开发
spring:
  profiles: dev
server:
  port: 80
---
#生产
spring:
  profiles: pro
server:
  port: 81
---
#测试
spring:
  profiles: test
server:
  port: 82
---
  1. 打包并开启服务器后,查看端口号
端口号为81

那么关于Maven的测试就到这里结束

SpringBoot配置文件分类

我们的环境配置可以写于许多位置,由此我们大致分为四类:

  1. classpath:application.yml[最低](Resources的一层配置中)
  1. classpath:config/application.yml(Resources的二层配置中)
  1. classpath:config/application.yml(package后jar包同目录下的配置文件)
  1. file:config/application.yml[最高]

我们将这些位置进行分类并排出优先级:

  • 1级:file:config/application.yml[最高]
  • 2级:file:application.yml
  • 3级:classpath:config/application.yml
  • 4级:classpath:application.yml[最低]

不同位置环境配置作用:

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

SpringBoot整合第三方技术

在基本介绍了SpringBoot之后,我们介绍最重要的一部分——整合第三方技术

下面我们以三个小案例来展现SpringBoot的整合

整合JUnit

SpringBoot是用于简化Spring的工具,所以我们分别从Spring和SpringBoot的视角进行整合

Spring整合JUnit

我们先给出Spring整合JUnit的代码:

// 设置运行器
@RunWith(SpringJUnit4ClassRunner.class)
// 加载环境
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTesst{
    
    // 自动装配测试对象
    @Autowired
    private BookService bookService;
    
    // 测试方法
    @Test
    public void testSave(){
		bookService.save();
    }
}

SpringBoot整合JUnit

我们从头说起:

  1. 创建新项目(这次我们只整合JUnit,所以我们的技术选择选择空白)
  1. 我们首先查看pom.xml并进行部分讲解


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.0
         
    
    com.itheima
    springboot_07_test
    0.0.1-SNAPSHOT
    
        1.8
    
    
        
        
            org.springframework.boot
            spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


  1. 项目自带有一个测试Java类
// 这里就是包,倘若为com.itheima1,classes需要设置为启动类.class
package com.itheima;

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

// 设置JUnit加载的SpringBoot启动类(类似于@RunWith和@ContextConfiguration的整合)
@SpringBootTest
class Springboot07TestApplicationTests {

    // 自动装配测试对象(未发生变化)
    @Autowired
    private BookService bookService;

    // 测试方法(未发生变化)
    @Test
    public void save() {
        bookService.save();
    }

}
/*
名称:@SpringBootTest
类型:测试类注解
位置:测试类定义上方
作用:设置JUnit加载的SpringBoot启动类
相关属性:
	classes:设置SpringBoot启动类
注意点:
	如果该测试类在SpringBoot启动类的包或子包中,可以省略启动类的设置,也就是省略classes的设定
	当该测试类与启动主Java类不属于同一目录名称下时,需要设置classes属性为启动类
	@SpringBootTest(classes = Springboot07TestApplication.class)
*/

整合MyBatis

我们如果想要采用SpringBoot整合SSM,那么就需要同时整合以下三门技术:

  • Spring
  • SpringMVC
  • MyBatis

但SpringBoot本身就是为了简化Spring,SpringMVC而存在,所以这两部分整合实际上我们已经完成了

所以我们将MyBatis单列出来提前进行整合学习,为后续的SSM整合打下基础##

Spring整合MyBatis

Spring对MyBatis的整合主要从三部分进行:

  • SpringConfig
    • 导入JdbcConfig
    • 导入MyBatisConfig
  • JdbcConfig
    • 定义数据源(加载properties项:driver,url,username,password)
  • MyBatisConfig
    • 定义sqlSessionFactoryBean
    • 定义映射配置

我们在这里就不做赘述了,如果遗忘可以查看之前的MyBatis文章

SpringBoot整合MyBatis

我们同样从头开始整合:

  1. 创建项目(这次我们需要MyBatis和Mysql两门技术栈)
  1. 查看pom.xml并稍作讲解


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.5.0
	
	com.itheima
	springboot_08_mybatis
	0.0.1-SNAPSHOT
	
		1.8
	
	
        
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.2.0
		

        
		
			mysql
			mysql-connector-java
			runtime
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

        
		
			com.alibaba
			druid
			1.1.16
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


  1. 创建与数据库相同的实体类
package com.itheima.domain;

public class Book {
    private Integer id;
    private String name;
    private String type;
    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
  1. 数据层实现
package com.itheima.dao;

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

// 注意:我们SpringBoot整合中的SpringConfig已经被省略,所以我们的JdbcConfig和MyBatisConfig配置类不用配置
// JdbcConfig主要用于配置DataSource,我们将会在yaml配置文件中配置
// MyBatisConfig配置sqlSessionFactoryBean,大部分属于固定代码,唯一的变量setTypeAliasesPackage我们选择设置整个代码包
// MyBatisConfig配置MapperScannerConfigurer映射地址,我们选择在dao数据层采用@Mapper来代替操作
@Mapper
public interface BookDao {
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
}
  1. 配置数据库关联
# 直接配置datasource即可
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
  1. 启动服务器即可
package com.itheima;

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

@SpringBootApplication
public class Springboot08MybatisApplication {

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

}
  1. 简单测试
package com.itheima;

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

@SpringBootTest
class Springboot08MybatisApplicationTests {

	@Autowired
	private BookDao bookDao;

	@Test
	void testGetById() {
		Book book = bookDao.getById(1);
		System.out.println(book);
	}

}

整合SSM

我们SpringBoot的最后课程就是用来整合SSM

我们同样采用和之前SSM案例整合的代码对比来介绍SpringBoot的SSM整合

Spring整合SSM

我们先给出之前SSM整合的大致框架:

我们来简单介绍上述代码的作用不做具体代码展示了(如有需要可以查看之前文章SSM整合):

  • Config文件夹:各种技术的Java配置类
  • SpringMvcSupport:拦截器,用来控制相关页面展示
  • controller文件夹:服务层
  • Code:状态码集合
  • ProjectExceptionAdvice:异常处理类
  • Result:返回内容集合
  • dao文件夹:数据层
  • domain文件夹:实现类
  • exception文件夹:异常类
  • service文件夹:业务层接口以及实现类
  • resources文件夹:相关配置文件(jdbc配置文件内容)
  • webapp文件夹:前端代码
  • pom.xml:各种依靠坐标

SpringBoot整合SSM

由于我们的SSM内容过多,我们针对上次的SSM案例进行整合,部分内容不做修改,我们仅介绍更改部分

下面让我们开始运行SpringBoot开始整合:

  1. 创建项目(运用了web,Mybatis,mysql技术栈)
  1. 查看pom.xml


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.5.0
		 
	
	com.itheima
	springboot_09_ssm
	0.0.1-SNAPSHOT
	springboot_09_ssm
	Demo project for Spring Boot
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.2.0
		

		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
		
			com.alibaba
			druid
			1.1.16
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


  1. 设置相关数据源,端口等(yaml)
# TODO 配置数据源相关信息

server:
  port: 80

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ssm_db
    username: root
    password: root
  1. 对dao数据层进行简单修改(添加@Mapper)
// 我们前面有提起Config文件夹全部删除,导致我们需要手动配置dao的数据层映射

package com.itheima.dao;

import com.itheima.domain.Book;
import org.apache.ibatis.annotations.*;

import java.util.List;

// TODO 添加@Mapper
@Mapper
public interface BookDao {
    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List getAll();
}
  1. 我们将页面相关内容移至Sources文件夹下的static文件夹下
  1. 基本修改完毕,采用测试类测试
package com.itheima.service;

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

import java.util.List;

@SpringBootTest
public class BookServiceTest {

    @Autowired
    private BookService bookService;

    @Test
    public void testGetById(){
        Book book = bookService.getById(2);
        System.out.println(book);
    }

    @Test
    public void testGetAll(){
        List all = bookService.getAll();
        System.out.println(all);
    }

}

最后为大家展示一下SpringBoot整合后的整体框架:

结束语

好的,关于SpringBoot的内容就介绍到这里,希望能为你带来帮助!

附录

该文章属于学习内容,具体参考B站黑马程序员李老师的SSM框架课程

这里附上链接:SpringBoot-01-SpringBoot工程入门案例开发步骤_哔哩哔哩_bilibili


新闻标题:一篇文章带你掌握主流办公框架——SpringBoot
文章出自:http://cdkjz.cn/article/dscgejc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220