一:新建SpringBoot3工程
https://start.spring.io/
⭐①新建SpringBoot3工程,下载压缩包解压后用IDEA打开
⭐②删减不需要的文件,application文件后缀改为yml,并清空里面的内容
⭐③设置编码
⭐④设置MAVEN
二:配置SpringBoot3工程
⭐①application.yml:配置 MySQL 数据库连接的配置项
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver // 统一固定的
username: root // 用户名
password: root // 密码
url: jdbc:mysql://localhost:3306/xm-pro?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false //xm-pro:数据库名称
😊数据库的连接地址,格式为:
3306:MySQL的默认端口 连接参数为固定的
jdbc:mysql://<主机名>:<端口号>/<数据库名称>?<连接参数>
三:写一个测试接口 say:hello
四:统一返回包装类Result
统一后端返回的数据类型
public class Result {
private String code;
private String msg;
private Object data;
public Result() {
}
public static Result success() {
Result result = new Result();
result.setCode("200");
result.setMsg("请求成功");
return result;
}
public static Result success(Object data) {
Result result = success();
result.setData(data);
return result;
}
public static Result error() {
Result result = new Result();
result.setCode("500");
result.setMsg("系统异常");
return result;
}
public static Result error(String code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
// Getters and Setters
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
五:全局异常处理
import com.example.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice("com.example.controller")
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody // 返回JSON格式
public Result error(Exception e) {
e.printStackTrace();
return Result.error();
}
@ExceptionHandler(CustomException.class)
@ResponseBody // 返回JSON格式
public Result error(CustomException e) {
e.printStackTrace();
return Result.error(e.getCode(),e.getMsg());
}
}
六:自定义异常
package com.example.exception;
public class CustomException extends RuntimeException {
private String code;
private String msg;
public CustomException(String code,String msg){
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}