目录
1,SpringBoot简介
做到这只是将工程的架子搭起来。要想被外界访问,最起码还需要提供一个 Controller 类,在该类中提供一个方法。
4. 编写 Controller 类
1.1 SpringBoot快速入门
1.1.1 开发步骤
SpringBoot 开发起来特别简单,分为如下几步:1.创建新模块,选择 Spring 初始化,并配置模块相关基础信息2.选择当前模块需要使用的技术集3.开发控制器类4.运行自动生成的 Application 类
对 SpringBoot 工程进行相关的设置我们使用这种方式构建的 SpringBoot 工程其实也是 Maven 工程,而该方式只是一种快速构建的方式而已。
注意:打包方式这里需要设置为 Jar
经过以上步骤后就创建了如下结构的模块,它会帮我们自动生成一个 Application 类,而该类一会再启动服务器时会用到
2 创建 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!";
}
}
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);
}
}
<?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.5.0</version>
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot_01_quickstart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- JDK的版本-->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 该依赖就是我们在创建 SpringBoot 工程勾选的那个 Spring Web 产生的- -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 依赖排除,排除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>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>
1.1.2 对比
坐标Spring 程序中的坐标需要自己编写,而且坐标非常多SpringBoot 程序中的坐标是我们在创建工程时进行勾选自动生成的web3.0 配置类Spring 程序需要自己编写这个配置类。这个配置类大家之前编写过,肯定感觉很复杂SpringBoot 程序不需要我们自己书写配置类Spring/SpringMVC 程序的配置类需要自己书写。而 SpringBoot 程序则不需要书写。注意:基于 Idea 的 Spring Initializr 快速构建 SpringBoot 工程时需要联网。
1.1.3 官网构建工程
然后点击 Spring Initializr 超链接就会跳转到如下页面
打开下载好的压缩包可以看到工程结构和使用 Idea 生成的一模一样,如下图
而打开 pom.xml 文件,里面也包含了父工程和 Spring Web 的依赖。
通过上面官网的操作,我们知道 Idea 中快速构建 SpringBoot 工程其实就是使用的官网的快速构建组件,那以后即使没有 Idea 也可以使用官网的方式构建 SpringBoot 工程。
1.1.4 SpringBoot工程快速启动
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
所以我们只需要使用 Maven 的 package 指令打包就会在 target 目录下生成对应的 Jar 包。
注意:该插件必须配置,不然打好的 jar 包也是有问题的。
java -jar springboot_01_quickstart-0.0.1-SNAPSHOT.jar
1.2 SpringBoot概述
SpringBoot 是由 Pivotal 团队提供的全新框架,其设计目的是用来 简化 Spring 应用的 初始搭建 以及 开发过程 。大家已经感受了 SpringBoot 程序,回过头看看 SpringBoot 主要作用是什么,就是简化 Spring 的搭建过程和开发过程。原始 Spring 环境搭建和开发存在以下问题:配置繁琐依赖设置繁琐SpringBoot 程序优点恰巧就是针对 Spring 的缺点自动配置。这个是用来解决 Spring 程序配置繁琐的问题起步依赖。这个是用来解决 Spring 程序依赖设置繁琐的问题辅助功能(内置服务器 ,... )。我们在启动 SpringBoot 程序时既没有使用本地的 tomcat 也没有使用 tomcat 插件,而是使用 SpringBoot 内置的服务器。
1.2.1 起步依赖
这些依赖就是启动依赖,接下来我们探究一下他是如何实现的。
再进入到该父工程中,在该工程中我们可以看到配置内容结构如下图所示
总而言之,父工程中properties是进行插件和依赖的版本管理,dependencyManagement是对所需的依赖的版本进行限制,防止不同依赖版本之间的冲突,build中有一个pluginManagement也可以对插件进行限制。
看完了父工程中 pom.xml 的配置后不难理解我们工程的的依赖为什么都没有配置 version 。
进入到该依赖,查看 pom.xml 的依赖会发现它引入了如下的依赖
starterSpringBoot 中常见项目名称,定义了当前项目使用的所有项目坐标,以达到减少依赖配置的目的parent所有 SpringBoot 项目要继承的项目,定义了若干个坐标版本号(依赖管理,而非依赖),以达到减少依赖冲突的目的spring - boot - starter - parent ( 2.5.0 )与 spring - boot - starter - parent ( 2.4.6 )共计 57 处坐标版本不同实际开发使用任意坐标时,仅书写 GAV 中的 G 和 A , V 由 SpringBoot 提供G : groupidA : artifactIdV : version如发生坐标错误,再指定 version (要小心版本冲突)
1.2.2 程序启动
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 依赖排除,排除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>
2,配置文件
2.1 配置文件格式
注意: SpringBoot 程序的配置文件名必须是 application ,只是后缀名不同而已。
在该工程中的 com.itheima.controller 包下创建一个名为 BookController 的控制器。内容如下:
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
2.1.2 不同配置文件演示
application.properties 配置文件内容如下: server.port=80
server:
port: 81
server:
port: 83
弹出如下窗口,按图中标记红框进行选择
通过上述操作,会弹出如下窗口
点击上图的 + 号,弹出选择该模块的配置文件
通过上述几步后,就可以看到如下界面。 properties 类型的配合文件有一个, ymal 类型的配置文件有两个
2.1.3 三种配合文件的优先级
2.2 yaml格式
优点:容易阅读yaml 类型的配置文件比 xml 类型的配置文件更容易阅读,结构更加清晰容易与脚本语言交互以数据为核心,重数据轻格式yaml 更注重数据,而 xml 更注重格式YAML 文件扩展名:.yml ( 主流 ).yaml上面两种后缀名都可以,以后使用更多的还是 yml 的。
2.2.1 语法规则
大小写敏感属性层级关系使用多行描述,每行结尾使用冒号结束使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许使用 Tab 键)空格的个数并不重要,只要保证同层级的左侧对齐即可。属性值前面添加空格(属性名与属性值之间使用冒号 + 空格作为分隔)# 表示注释
2.3 yaml配置文件数据读取
2.3.1 环境准备
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
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;
}
}
lesson: SpringBoot
server:
port: 80
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2.3.2 读取配置数据
@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!";
}
}
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封装全配置数据
@Autowired
private Environment environment;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
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!";
}
}
//封装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;
}
}
@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!";
}
}
2.4 多环境配置
来回的修改配置会很麻烦,而 SpringBoot 给开发者提供了多环境的快捷配置,需要切换环境时只需要改一个配置即可。不同类型的配置文件多环境开发的配置都不相同,接下来对不同类型的配置文件进行说明
2.4.1 yaml文件
在 application.yml 中使用 --- 来分割不同的配置,内容如下
---
#开发
spring:
config:
activate:
on-profile: dev
server:
port: 80
---
#生产
spring:
profiles: pro
server:
port: 81
---
#测试
spring:
profiles: test
server:
port: 82
---
#设置启用的环境
spring:
profiles:
active: dev
2.4.2 properties文件
2.4.3 命令行启动参数设置
2.5 配置文件分类
2.5.1 代码演示
通过这个结果可以得出类路径下的 config 下的配置文件优先于类路径下的配置文件。
在硬盘上找到 jar 包所在位置
3,SpringBoot整合junit
3.1 环境准备
3.2 编写测试类
@SpringBootTest(classes = Springboot07TestApplication.class)
class Springboot07TestApplicationTests {
@Autowired
private BookService bookService;
@Test
public void save() {
bookService.save();
}
}
注意: 这里的引导类所在包必须是测试类所在包及其子包。例如:引导类所在包是 com.itheima测试类所在包是 com.itheima如果不满足这个要求的话,就需要在使用 @SpringBootTest 注解时,使用 classes 属性指定引导类的字节码对象。如@SpringBootTest(classes = Springboot07TestApplication.class)
4,SpringBoot整合mybatis
4.1 回顾Spring整合Mybatis
4.2 SpringBoot整合mybatis
4.2.1 创建模块
选择当前模块需要使用的技术集(MyBatis、MySQL)
4.2.2 定义实体类
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;
}
}
4.2.3 定义dao接口
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.2.4 定义测试类
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
4.2.5 编写配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
4.2.6 测试
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.2.7 使用Druid数据源
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
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
5,案例
5.1 创建工程
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
@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<Book> all = bookService.getAll();
System.out.println(all);
}
}
5.3 配置文件
# 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 #?servierTimezone=UTC
username: root
password: root