springboot简述

news/2024/10/17 17:22:09/

文章目录

    • 一、SpringBoot简介
      • 1、springboot快速入门
        • 1、开发步骤
          • 1.创建springboot入门项目
          • 2.创建controller
          • 3.启动服务器
          • 4.测试
        • 2、对比spring
        • 3、springboot工程快速启动
        • 4.切换web服务器
    • 二、配置文件
      • 1.配置文件格式
      • 2.properties配置文件
      • 3.yaml格式配置文件
        • 1.语法规则
        • 2.yaml配置文件的数据读取
          • 1.使用@value注解
          • 2.使用Environment对象
          • 3.自定义对象
    • 三、springboot整合junit
    • 四、springboot整合mybatis
      • 1.回顾一下spring整合mybatis
      • 2.springboot整合mybatis
        • 1.创建一个全新的模块导入相关依赖
        • 2.定义实体类
        • 3.定义dao接口
        • 4.定义测试类
        • 5.编写配置
        • 6.注意
        • 7.运行测试类
    • 五、结语

一、SpringBoot简介

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

使用了 Spring 框架后已经简化了我们的开发。而 SpringBoot 又是对 Spring 开发进行简化的,可想而知 SpringBoot 使用的简单及广泛性。

1、springboot快速入门

1、开发步骤

SpringBoot 开发起来特别简单,分为如下几步:

  • 创建新模块,选择Spring初始化,并配置模块相关基础信息
  • 选择当前模块需要使用的技术集
  • 开发控制器类
  • 运行自动生成的Application类
1.创建springboot入门项目

在这里插入图片描述
在这里插入图片描述
经过以上步骤后就创建了如下结构的模块,它会帮我们自动生成一个 Application 类,而该类一会在启动服务器时会用到,其实它就是服务器,springboot自身包含服务器,不需要我们导入服务器了。
在这里插入图片描述

== 注意:==

  1. 在创建好的工程中不需要创建配置类

  2. 创建好的项目会自动生成其他的一些文件,而这些文件目前对我们来说没有任何作用,所以可以将这些文件删除。

    可以删除的目录和文件如下:

    • .mvn
    • .gitignore
    • HELP.md
    • mvnw
    • mvnw.cmd
2.创建controller

com.example.controller 包下创建 BookController ,代码如下:

@RestController
@RequestMapping("/books")
public class BookController {@GetMapping("/{id}")public String getById(@PathVariable Integer id){System.out.println("id==>"+id);return "hello,springboot!";}
}

在这里插入图片描述

3.启动服务器

运行 SpringBoot 工程不需要使用本地的 Tomcat 和 插件,只运行项目 com.example 包下的 Application 类,我们就可以在控制台看出如下信息
在这里插入图片描述

4.测试

使用apifox工具进行测试
在这里插入图片描述
在这里插入图片描述

至此入门案例已经开发完成,我们写的只有controller层的一些内容,复杂的配置都省略了。

2、对比spring

在这里插入图片描述

  • 坐标

    Spring 程序中的坐标需要自己编写,而且坐标非常多

    SpringBoot 程序中的坐标是我们在创建工程时进行勾选自动生成的

  • web3.0配置类

    Spring 程序需要自己编写这个配置类。这个配置类大家之前编写过,肯定感觉很复杂

    SpringBoot 程序不需要我们自己书写

  • 配置类

    Spring/SpringMVC 程序的配置类需要自己书写。而 SpringBoot 程序则不需要书写。

注意:基于Idea的 Spring Initializr 快速构建 SpringBoot 工程时需要联网。

3、springboot工程快速启动

以后我们和前端开发人员协同开发,而前端开发人员需要测试前端程序就需要后端开启服务器,这就受制于后端开发人员。为了摆脱这个受制,前端开发人员尝试着在自己电脑上安装 TomcatIdea ,在自己电脑上启动后端程序,这显然不现实。

我们后端可以将 SpringBoot 工程打成 jar 包,该 jar 包运行不依赖于 TomcatIdea 这些工具也可以正常运行,只是这个 jar 包在运行过程中连接和我们自己程序相同的 Mysql 数据库即可。这样就可以解决这个问题,如下图
在这里插入图片描述
在打包之前确认自己是否导入打包插件,在我们创建springboot工程时默认是给我们导入好的,这里只是提一下,如果没有这个插件,打包好的jar包是有问题的。

<plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version>
</plugin>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
输入命令java -jar springboot_01-0.0.1-SNAPSHOT.jar启动工程,启动完成后我们依然可以通过apifox进行测试
在这里插入图片描述

4.切换web服务器

现在我们启动工程使用的是 tomcat 服务器,那能不能不使用 tomcat 而使用 jetty 服务器,而要切换 web 服务器就需要将默认的 tomcat 服务器给排除掉,怎么排除呢?使用 exclusion 标签
在这里插入图片描述
在这里插入图片描述
这样服务器就切换成功了,测试方法不变。

二、配置文件

1.配置文件格式

在这里以端口号的编写举例,主要有三种格式

  • application.properties

    server.port=80
    
  • application.yml

    server:port: 81
    
  • application.yaml

    server:port: 82
    

注意:SpringBoot 程序的配置文件名必须是 application ,只是后缀名不同而已。

2.properties配置文件

在这里简单配置了一下应用名称和端口号

# 应用名称
spring.application.name=springboot_01
# 应用服务 WEB 访问端口
server.port=8080

3.yaml格式配置文件

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

最开始我们使用的是xml,格式如下:

<enterprise><name>mu</name><age>18</age><tel>111111</tel>
</enterprise>

properties 类型的配置文件如下

enterprise.name=mu
enterprise.age=18
enterprise.tel=111111

yaml 类型的配置文件内容如下

enterprise:name: muage: 18tel: 111111

优点:

  • 容易阅读

    yaml 类型的配置文件比 xml 类型的配置文件更容易阅读,结构更加清晰

  • 容易与脚本语言交互

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

    yaml 更注重数据,而 xml 更注重格式

YAML 文件扩展名:

  • .yml (主流)
  • .yaml

上面两种后缀名都可以,以后使用更多的还是 yml 的。

1.语法规则

  • 大小写敏感
  • 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用Tab键)空格的个数并不重要,只要保证同层级的左侧对齐即可。
  • 属性值前面添加空格(属性名与属性值之间使用冒号+空格作为分隔

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

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

enterprise:name: muage: 18tel: 111111subject:- Java- 前端- 大数据

2.yaml配置文件的数据读取

1.使用@value注解

注解中用于读取属性名引用方式是:${一级属性名.二级属性名……}

我们可以在 BookController 中使用 @Value 注解读取配合文件数据,如下

@RestController
@RequestMapping("/books")
public class BookController {@Value("${server.port}")private Integer port;@Value("${enterprise.name}")private String name;@GetMapping("/{id}")public String getById(@PathVariable Integer id){System.out.println(port);System.out.println(name);return "hello,springboot!";}
}

我们创建一个enterprise实体类来封装数据

public class Enterprise {private String name;private int age;private String tel;private String[] subject;//setter and getter//toString
}

写yaml配置文件

server:port: 81
enterprise:name: muage: 18tel: 11111subject:- Java- 前端- 大数据

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

2.使用Environment对象

上面方式读取到的数据特别零散,SpringBoot 还可以使用 @Autowired 注解注入 Environment 对象的方式读取数据。这种方式 SpringBoot 会将配置文件中所有的数据封装到 Environment 对象中,如果需要使用哪个数据只需要通过调用 Environment 对象的 getProperty(String name) 方法获取。具体代码如下:

@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate Environment env;@GetMapping("/{id}")public String getById(@PathVariable Integer id) {System.out.println(env.getProperty("server.port"));System.out.println(env.getProperty("enterprise.name"));return "hello,springboot!";}
}

注意:这种方式,框架内容大量数据,而在开发中我们很少使用。

3.自定义对象

SpringBoot 还提供了将配置文件中的数据封装到我们自定义的实体类对象中的方式。具体操作如下:

  • 将实体类 bean 的创建交给 Spring 管理。

    在类上添加 @Component 注解

  • 使用 @ConfigurationProperties 注解表示加载配置文件

    在该注解中也可以使用 prefix 属性指定只加载指定前缀的数据

  • BookController 中进行注入

Enterprise 实体类内容如下:

@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {private String name;private int age;private String tel;private String[] subject;//setter and getter//toString
}

BookController 内容如下:

@RestController
@RequestMapping("/books")
public class BookController {@Autowiredprivate Enterprise ent;@GetMapping("/{id}")public String getById(@PathVariable Integer id) {System.out.println(ent.getName());System.out.println(ent.getSubject()[0]);return "hello,springboot!";}
}

注意:

使用第三种方式,在实体类上有如下警告提示
在这里插入图片描述

这个警告提示解决是在 pom.xml 中添加如下依赖即可

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

运行测试
在这里插入图片描述
在这里插入图片描述

三、springboot整合junit

步骤:

  • 在测试类上添加 SpringBootTest 注解
  • 使用 @Autowired 注入要测试的资源
  • 定义测试方法进行测试

创建一个全新springboot项目,创建时导入junit测试依赖
在这里插入图片描述
在这里插入图片描述

com.example.service 下创建 BookService 接口,内容如下

public interface BookService {public void save();
}

com.example.service.impl 包写创建一个 BookServiceImpl 类,使其实现 BookService 接口,内容如下

@Service
public class BookServiceImpl implements BookService {public void save() {System.out.println("book service is running ...");}
}

编写测试类

@SpringBootTest
class SpringbootJunitApplicationTests {@Autowiredprivate BookService bookService;@Testvoid save() {bookService.save();}
}

运行服务器
在这里插入图片描述
==注意:==这里的引导类所在包必须是测试类所在包及其子包。

例如:

  • 引导类所在包是 com.example
  • 测试类所在包是 com.example
  • 一定要在实现类上加上@service使其能够被spring加载为bean管理,否则会报错

如果不满足这个要求的话,就需要在使用 @SpringBootTest 注解时,使用 classes 属性指定引导类的字节码对象。如 @SpringBootTest(classes = Springboot07TestApplication.class)

四、springboot整合mybatis

1.回顾一下spring整合mybatis

Spring 整合 Mybatis 需要定义很多配置类

  • SpringConfig 配置类

    • 导入 JdbcConfig 配置类

    • 导入 MybatisConfig 配置类

      @Configuration
      @ComponentScan("com.example")
      @PropertySource("classpath:jdbc.properties")
      @Import({JdbcConfig.class,MyBatisConfig.class})
      public class SpringConfig {
      }
      
  • JdbcConfig 配置类

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

      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;@Beanpublic DataSource getDataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(userName);ds.setPassword(password);return ds;}
      }
      
  • MybatisConfig 配置类

    • 定义 SqlSessionFactoryBean

    • 定义映射配置

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

2.springboot整合mybatis

1.创建一个全新的模块导入相关依赖

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

2.定义实体类

com.example.domain 包下定义实体类 User,内容如下

public class User {private Integer id;private String name;//setter and getter//toString
}

3.定义dao接口

@Mapper
public interface UserDao {@Select("select * from tbl_user where id = #{id}")public User getById(Integer id);
}

4.定义测试类

@SpringBootTest
class SpringbootMybatisApplicationTests {@Autowiredprivate UserDao userDao;@Testvoid testGetById() {User user = userDao.getById(3);System.out.println(user);}
}

5.编写配置

我们代码中并没有指定连接哪儿个数据库,用户名是什么,密码是什么。所以这部分需要在 SpringBoot 的配置文件中进行配合。

使用druid数据源

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

这里我使用的是创建springboot项目后自带的properties配置文件,个人感觉还挺好用的,我们对里面的一些配置进行修改

# 应用名称
spring.application.name=springboot_mybatis
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.example.mybatis.entity
# 数据库驱动:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=****
spring.datasource.password=****

6.注意

Mybatis 会扫描接口并创建接口的代码对象交给 Spring 管理,但是现在并没有告诉 Mybatis 哪个是 dao 接口。而我们要解决这个问题需要在BookDao 接口上使用 @Mapper

注意:

SpringBoot 版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区 jdbc:mysql://localhost:3306/blue?serverTimezone=UTC,或在MySQL数据库端配置时区解决此问题

7.运行测试类

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

至此springboot整合mybatis完成,主要就是在创建springboot工程时导入依赖,然后编写接口,在测试类中注入接口,在接口上使用**@mapper注解让其被spring管理**并加载为一个bean

五、结语

感谢各位大佬的浏览,有什么问题大家可以指出,私信或者评论都是可以的,互相学习~


http://www.ppmy.cn/news/807.html

相关文章

【python与数据分析】实验十三 北京市空气质量

目录 一、实验内容 二、完成情况 三、数据分析 1.问题描述 2.编程思路 3.程序代码 4.程序运行结果 &#xff08;1&#xff09;2014年-2019年AQI时间序列折线图 &#xff08;2&#xff09;各年AQI折线图、AQI直方图、PM2.5与AQI散点图、空气质量整体情况的饼图 ​&am…

HTML+CSS大作业:众志成城 抗击疫情 抗击疫情网页制作作业 疫情防控网页设计

&#x1f389;精彩专栏推荐 &#x1f4ad;文末获取联系 ✍️ 作者简介: 一个热爱把逻辑思维转变为代码的技术博主 &#x1f482; 作者主页: 【主页——&#x1f680;获取更多优质源码】 &#x1f393; web前端期末大作业&#xff1a; 【&#x1f4da;毕设项目精品实战案例 (10…

import一个“太极”库,让Python代码提速100倍

众所周知&#xff0c;Python的简单和易读性是靠牺牲性能为代价的—— 尤其是在计算密集的情况下&#xff0c;比如多重for循环。 不过现在&#xff0c;大佬胡渊鸣说了&#xff1a; 只需import 一个叫做“Taichi”的库&#xff0c;就可以把代码速度提升100倍&#xff01; 不信&…

网格化微型空气质量站是什么?系统参数?工作特点?

产品简介 网格化微型空气质量站是一种集数据采集、存储、传输和管理于一体的无人值守的环境监测系统&#xff0c;能全天候、连续、自动地监测环境&#xff0c;在提供PM10、PM2.5、 SO2、 NO2、CO、O3等参数数据的基础上&#xff0c;可扩展对VOCs、氯气、硫化氢、氨气等多种特征…

Spark中常用的聚合算子说明及使用

一、groupByKey 1、基本释义 groupByKey 顾名思义是“按照 Key 做分组”&#xff0c;但实际上groupByKey算子包含分组和收集两步。具体来说&#xff0c;对于元素类型为&#xff08;Key&#xff0c;Value&#xff09;键值对的 Paired RDD&#xff0c;groupByKey 的功能就是对 …

浅谈正则表达式——C++正则替换引起的性能下降

目录问题引入正则替换测试常规方法测试模拟外部多次调用正则性能差的原因写在最后问题引入 最近在一次解析大文件(10万行)时&#xff0c;处理空格用到了正则替换&#xff0c;却没想到带来了性能上的问题&#xff0c;特别在此记录给需要的人避坑。假如要用C处理一个字符串首尾的…

Python编程 顺序执行与程序的主入口

作者简介&#xff1a;一名在校计算机学生、每天分享Python的学习经验、和学习笔记。 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a;网络豆的主页​​​​​​ 目录 前言 一.顺序执行 1.顺序执行(了解) 2.程序主入口(熟悉) 前言 本章将会讲解P…

17条卢松松近期言论汇总

我是卢松松&#xff0c;点点上面的头像&#xff0c;欢迎关注我哦&#xff01; 本文汇集了前段时间卢松松写的段子&#xff0c;有心情感悟、工作感悟、做直播带货、创业的感悟。关注互联网、草根创业者的朋友可以看看&#xff01; (1) 人最舒服的是什么时候呢?我认为&#xff…