黑马程序员SpringBoot2全套视频教程,springboot零基础到项目实

# 1.SpringBoot
## 1.Rest风格
### 1.1Rest
#### 1.1.1 Rest简介
* Rest 表现形式状态转换
**传统风格**
- http://localhost/user/getById?id=1
- http://localhost/user/saveUser
**Rest风格**
- http://localhost/user/1 (查询单数,删除用户信息)
- http://localhost/user (查询复数,添加,修改用户信息)
**优点**
* 隐藏资源访问行为
* 书写简化
#### 1.1.2 地址栏传参模式----参数配置
* method = RequestMethod.GET 查询
* method = RequestMethod.POST 保存
* method = RequestMethod.DELETE 删除
* method = RequestMethod.HEAD
* method = RequestMethod.PUT 更新
* method = RequestMethod.OPTIONS
* method = RequestMethod.PATCH
* method = RequestMethod.TRACE
```
package top.wabisabifag.controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class UserController {
@RequestMapping(value = "/users",method = RequestMethod.POST)
@ResponseBody
public String save(){
System.out.println("user save...");
return "{'module':'user save'}";
}
/**
* {id} 代表请求格式,对应方法的传参值
* @PathVariable 指定 id 的所取值,url地址传给方法
*/
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id){
System.out.println("user delete..."+id);
return "{'module':'user delete'}";
}
@RequestMapping(value = "/users",method = RequestMethod.PUT)
@ResponseBody
public String update(@RequestBody User user){
System.out.println("user update..."+user);
return "{'module':'user update'}";
}
/*
* @RequestMethod.GET 专门查询语句
*/
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
@ResponseBody
public String getById(@PathVariable Integer id){
System.out.println("user getById..."+id);
return "{'module':'user getById'}";
}
@RequestMapping(value = "/users",method = RequestMethod.GET)
@ResponseBody
public String getAll(){
System.out.println("user getAll...");
return "{'module':'user getAll'}";
}
}
```
总结:
区别
* @RequestParam 用于接受 url 地址传参或表单传参
* @RequestBody 用于接受json数据
* @PathVariable 用于接收路径参数,使用 {name} 描述路径参数
应用
* 后期开发,发送请求超过一个参数,以json格式,@RequestBody 应用为主
* 如果发送非json格式数据,选用@RequestParam 接收请求参数
* 采用RESTful进行开发,当参数较少时,采用@PathVariable 接收请求路径变量,传递 id 值
#### 1.1.3 Rest快速开发
```
package top.wabisabifag.controller;
import org.springframework.web.bind.annotation.*;
@RestController
@ResponseBody
//@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String save(@RequestBody User user){
System.out.println("user save...");
return "{'module':'user save'}";
}
/**
* {id} 代表请求格式,对应方法的传参值
* @PathVariable 指定 id 路径 的 所取值
*/
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("user delete..."+id);
return "{'module':'user delete'}";
}
@PutMapping
public String update(@RequestBody User user){
System.out.println("user update..."+user);
return "{'module':'user update'}";
}
/*
* @RequestMethod.GET 专门查询语句
*/
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("user getById..."+id);
return "{'module':'user getById'}";
}
@GetMapping
public String getAll(){
System.out.println("user getAll...");
return "{'module':'user getAll'}";
}
}
```
主要点:
简化
* @RestController 等价@ResponseBody < < ==== > > @RestController (目的:省略重复)
* value = "/users" 省略:value 但不能省略传递的 {name} 值
* method = RequestMethod. { } @...Mapping代替
单值 和 POJO值 的传值方式
* @PathVariable 单值传输
* @RequestBody POJO值传输
## 2.基础配置
[SpringBoot文档地址](https://docs.spring.io/spring-boot/docs/current/reference/html/)
### 2.1 属性配置
[SpringBoot Appilcation.properties文档地址](https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties)
#### 2.1.1 Springboot 多种属性配置(文件优先级递减)
- .properties
+ server.port=80
- .yml
+ server:
port: 80
- .yaml
+ server:
port: 80
##### 1.yml格式
1. 多层级属性名
```
a:
b:
C: 1145137
```
2. 数组属性名
```
likes:
- games
- foods
- books
# 缩略模式
likes:[games,foods,books]
```
3. 对象数组属性名
```
users:
- name: zhangsan
age: 18
- name: Jhon
age: 16
# 缩略模式
users:[{name:zhangsan,age:18},{name:Jhon,age:16}]
```
##### 2.数据读取
```
@value("${users.name}")
private String name;
@value("${likes[1]}")
private String games;
@value("${users[1].name}")
private String name;
application.properties
----------------------
baseDir: c:\windows
# 使用 ${value} 引用数据
tempDir: ${baseDir}\temp
---------------------
```
属性值(value)用 "\"转义字符 的会不显示
使用 “spring\boot\text.txt"
##### 3.封装数据
1. 全配置封装
```
//自动装配
@Autowired
private Environment environment;
environment.getProperty("users[0].name");
```
2. 针对性封装
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver: com.mysql.jdbc.Driver
---------------------
# 1.创建类,封装数据
package top.wabisabifag.POJO;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
# 2.Spring加载数据对象,告诉Spring加载信息
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class MyDataSource {
private String url;
private String username;
private String password;
private String driver;
@Override
public String toString() {
return "MyDataSource{" +
"url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", driver='" + driver + '\'' +
'}';
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
}
---------------------------------
# 3.使用Spring获取的信息
@Autowired
private MyDataSource myDataSource;
```
#### 2.1.2 修改服务器端口
```
# 配置服务器端口
server.port=80
# 修改Spring启动的banner
# 关闭Spring Logo
spring.main.banner-mode=off
# 将text,png等文件转化为二维图
#spring.banner.image.location=1.png
# 控制日志
# 输出日志级别
#logging.level.root=debug
# 在出错时输出日志
logging.level.root=error
```
## 3.第三方技术整合
### 1.JUnit
```
package top.wabisabifag.dao.Impl;
import org.springframework.stereotype.Repository;
import top.wabisabifag.dao.BookDao;
/* 3.接受Spring管理 */
@Repository
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("BookDao testing");
}
}
-------------------------------
package top.wabisabifag.test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import top.wabisabifag.dao.BookDao;
/* 4.获取Spring管理声明 */
@SpringBootTest
public class SpringBootJUnitApplicationTests {
/*1.注入测试对象*/
@Autowired
private BookDao bookDao;
/*2.执行测试方法*/
@Test
void contextLoads(){
bookDao.save();
}
}
```
1. 当test 测试路径无法对应java 源代码路径
@SpringBootTest(classes = BookDaoImpl.class)来申明源码
```
@SpringBootTest(classes = BookDaoImpl.class)
```
@RunWith(设置运行器)
@ContextConfiguration(class = .... ) //配置引导类或配置类
+ ContextConfiguration 用于在当前包下查找声明类
### 2.Mybatis
```
-------pom 获取MP依赖-----------
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
--------继承 BaseMapper-------
package top.wabisabifag.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import top.wabisabifag.POJO.Book;
@Mapper // 继承 BaseMapper
public interface BookDao extends BaseMapper {
public void save();
@Select("select * from smbms_user where userid = #{id} ")
public Book getById(int id);
}
----------使用MP方法--------------
package top.wabisabifag.test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import top.wabisabifag.dao.BookDao;
import top.wabisabifag.dao.Impl.BookDaoImpl;
@SpringBootTest(classes = BookDaoImpl.class)
public class SpringBootJUnitApplicationTests {
/*1.注入测试对象*/
@Autowired
private BookDao bookDao;
/*2.执行测试方法*/
@Test
void contextLoads(){
bookDao.save();
bookDao.getById(1);
}
@Test
void contextLoadsPlus(){
System.out.println(bookDao.selectById(2));
}
}
--------配置文件中相关数据库表名称映射-----------
#配置MP相关数据库名称
mybatis-plus:
global-config:
db-config:
table-prefix: tb_
```
### 4.Lombok
```
-------pom 获取Lombok依赖--------
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
--------POJO 实体类注解省略Get,Set--------
package top.wabisabifag.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data // @Getter @Setter
@NoArgsConstructor // 无参构造
@AllArgsConstructor // 有参构造
@ToString
public class User {
private int id;
private String userCode;
}
```
主要:
- @Getter @Setter 等价于 @Data
### 5.Druid
```
------pom 获取Druid依赖------
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
-------配置--------
通用配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/smbms_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
整合配置:
spring:
datasource:
druid:
url: jdbc:mysql://localhost:3306/smbms_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
```
## 2.SSMP整合案例
+ 实体类开发 使用Lombok 快速制作实体类
+ Dao 开发 整合MyBatisPlus ,制作数据层测试类
+ Service 开发 基于MyBatisPlus 进行增量开发,制作业务层测试类
+ Controller 开发 基于Restful 开发,使用PostMan 测试接口功能
+ Controller 开发 前后端开发协议制作
+ 页面开发 基于VUE,Element制作,前后端联,页面数据处理
- CRUD 分页,查询操作
+ 项目异常处理
+ 按条件查询 页面功能调整,Controller修正功能,Service修正功能
### SMMP源代码
[源代码]()
## 3.SpringBoot维护
### 1.工程运行
#### 1.Windows jar 包执行
```
1. 执行jar 包: java -jar packageName
2. 查询端口: netstat -ano
3. 查询指定端口: netstat -ano |findstr "端口号"
4. 根据进程PID 查询进程名称: tasklist |findstr "进程号PID号"
5. 根据PID 杀死任务: tasklist /F /PID "进程PID号"
6. 根据进程名称杀死任务: taskkill -f -t -im "进程名称" 进程名称有多个相同的
```
#### 2.Linux jar 包执行
```
1. 启动后端: nohup java -jar jarPackageName > server.log 2>&1 &
```
#### 3.临时属性配置
```
1. 执行jar 包: java -jar packageName --server.port=8080 --spring.datasouce.druid.password=root
2.
@SpringBootApplication
@MapperScan("top.wabisabifag.dao")/*使用@MapperScan可以指定要扫描的Mapper类的包的路径*/
@ComponentScan(basePackages={"top.wabisabifag"})
public class application {
public static void main(String[] args) {
// 线程安全问题
// SpringApplication.run(application.class,args);
// 不接受外部临时参数
SpringApplication.run(application.class);
}
}
3. application.yml 的双配置
文件位置: 1. web/springboot.jar/resources/application.yml
2. web/springboot.jar/resources/config/application.yml
3. web/application.yml
4. web/config/application.yml
重 复: 文件优先级配置高覆盖低的;
不重复: 互不干扰;
权限等级: 逐级上升(4 > 3 > 2 > 1)
文件内config/ .yml > 文件外 .properties
```
#### 4.多环境开发
##### 1. YAML
```
# 一、应用环境
spring:
profiles:
active: pro
---
# 二、设置环境
# 1. 公共环境
# 2. 自定义环境
spring:
profiles: pro
server:
port:80
---
spring:
profiles: dev
server:
port:81
---
spring:
config:
activate:
on-profiles: test
server:
port:82
```
###### YAML 弊端
1.--- : 分割线是格式需求
2.容易暴露信息,安全有问题
###### YAML 优化
生成配置文件:
application-dev.yml
application-pro.yml
application-test.yml
可以独立配置文件定义环境;
独立配置文件便于线上系统维护更新并保障系统安全性;
##### 2. properties
- 文件内容格式
```
spring.profiles=pro
server.port=80
---
spring.profiles=dev
server.port=81
---
spring.profiles=test
spring.profiles=82
```
- 生成配置文件:
application-dev.properties
application-pro.properties
application-test.properties
##### 3. 独立的功能配置文件
- 根据功能 对配置文件的信息拆分
+ application-devDB.yml
+ application-devRedis.yml
+ application-devMVC.yml
- application.yml 中使用include 属性在激活指定环境 条件下,同时对多环境进行加载
+ application.yml 后加载
```
spring:
profiles:
active: dev
include: devDB,devRedis,devMVC
```
###### 优化 include 无法动态更改问题
+ application.yml 前加载
SpringBoot 2.4.X 后:
```
spring:
profiles:
active: dev
group:
"dev": devDB,devRedis,devMVC
"pro": proDB,proRedis,proMVC
"test": testDB,testRedis,testMVC
```
##### 4. 多环境开发控制(Maven)
1. pom.xml
```
<!--设置多环境-->
<profiles>
<profile>
<id>env_dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
<!--设置默认启动-->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>env_pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
</profile>
</profiles>
```
2. application.yml
```
spring:
profiles:
<!-- 使用Maven 的环境配置的格式 "@....@" -->
active: @profile.active@
group:
"dev": devDB,devRedis,devMVC
"pro": proDB,proRedis,proMVC
"test": testDB,testRedis,testMVC
```
- ieda 对Maven 环境的更改无法生效,需要手动编译compile
#### 5. 日志
##### 1. 日志设置
1. 代码中使用日志工具记录日志
```
@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController {
private static final Logger log = (Logger) LoggerFactory.getLogger(UserController.class);
@GetMapping("/{id}")
public User getById(@PathVariable Integer id){
// application.yml debug:true
log.debug("debug...");
log.info("info...");
log.warning("warn...");
log.error();
log.fatal();
return userService.getById(id);
}
}
```
2. 设置日志级别
```
# 开启debug模式,输出调试信息,常用于检查系统运行状况
debug: true
# 设置日志级别 root表示根节点,整体应用日志级别
logging:
level:
root:
error
# 设置某包的日志级别
top.wabisabifag.controller: debug
# 设置分组,对某个祖设置日志级别
enable:warn
```
##### 2. 日志工具 (动态和继承)
1. 设置日志对象
```
package top.wabisabifag.controller.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.wabisabifag.controller.UserController;
public class LoggerClass {
private Class clazz = null;
public static Logger log;
public LoggerClass(){
clazz = this.getClass();
log = LoggerFactory.getLogger(UserController.class);
}
}
```
2. 日志工具引入控制层
```
package top.wabisabifag.controller.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@Slf4j // 开启日志
@RestController
@RequestMapping("/users")
@CrossOrigin
public class UserController3 extends LoggerClass {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
log.debug("debug...");
log.info("info...");
log.warning("warn...");
log.error("error...");
log.fatal();
return "springboot is running... 2";
}
}
```
##### 3. 日志输出格式
1. 控制台日志输出
```
# 日志配置
logging:
level:
root:
error
pattern:
console: "%d %clr(5p) --- [%16t] %clr(%-40.40c){red} :%m %n"
```
- d 日期
- p 信息的级别
- %clr(%5p) 颜色设置
- %5p 占据的长度
- [%16 t] 运行的文件
- %-40 左对齐
- .40c 截断后,容纳40长度
- m 消息
- n 换行
2. 日志记录
```
# 日志配置
logging:
level:
root:
error
# 控制台日志输出
pattern:
console: "%d %clr(5p) --- [%16t] %clr(%-40.40c){red} :%m %n"
# 日志文件记录
file:
name: server.log
# 日志分期记录
logback:
rollingpolicy:
max-file-size: 3KB
file-name-pattern: server.%d{yyyy-MM-dd}.%i.log
# 输出格式: server.2023-09-20.0.log
```
## 4.SpringBoot 应用开发
### 1. 热部署
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
```
在IEDA激活热部署: Ctrl + F9