lombok插件使用
引入依赖,在项目中使用Lombok可以减少很多重复代码的书写。比如说getter/setter/toString等方法的编写 ↓
org.projectlombok lombok 1.16.20
idea中安装lombok插件↓
创建包 entity 编写实体类 User.java(此处使用了 Lombok 简化代码) ↓`
@Data public class User { private Long id; private String name; private Integer age; private String email; }
点击查看注解编译结果↓
统一异常处理
我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理,
创建统一异常处理类GlobalExceptionHandler.java ↓
package com.ywj.handler; import com.ywj.constants.ResultCodeEnum; import com.ywj.exception.MyException; import com.ywj.util.ExceptionUtil; import com.ywj.vo.R; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice @Slf4j public class GlobalExceptionHandler { //全局异常处理 @ExceptionHandler(Exception.class) @ResponseBody public R error(Exception e){ //e.printStackTrace();//输出异常堆栈信息 log.error(e.getMessage()); return R.error(); } //特定异常处理 @ExceptionHandler(ArithmeticException.class) @ResponseBody public R error(ArithmeticException e){ //e.printStackTrace();//输出异常堆栈信息 //log.error(e.getMessage()); log.info("错误信息----------------------------"); log.error(e.getMessage()); return R.setResult(ResultCodeEnum.MY_ERROR); } //自定义异常处理 @ExceptionHandler(MyException.class) @ResponseBody public R error(MyException e){ //e.printStackTrace();//输出异常堆栈信息 //log.error(e.getMessage()); log.error(ExceptionUtil.getMessage(e)); return R.error().message(e.getMessage()).code(e.getCode()); } }
创建MyException.java通用异常类,继承RuntimeException↓
package com.ywj.exception; import com.ywj.constants.ResultCodeEnum; import lombok.Data; @Data //@ApiModel(value = "自定义全局异常类") public class MyException extends RuntimeException { //@ApiModelProperty(value = "状态码") private Integer code; /** * 接收状态码和错误消息 * @param code * @param message */ public MyException(Integer code, String message){ super(message); this.code = code; } public MyException(ResultCodeEnum resultCodeEnum){ super(resultCodeEnum.getMessage()); this.code = resultCodeEnum.getCode(); } @Override public String toString() { return "MyException{" + "code=" + code + ", message=" + this.getMessage() + '}'; } }
业务中需要的位置抛出自定义异常↓
package com.ywj.controller; import com.ywj.exception.MyException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("/") public String index(Model model){ //System.out.println(10/0); if (true){ throw new MyException(10086, "自定义异常"); } System.out.println("index"); model.addAttribute("name", "ywj"); return "index"; } }
依赖的其他类补充说明↓
统一结果返回类R↓
package com.ywj.vo; import com.ywj.constants.ResultCodeEnum; import lombok.Data; import java.util.HashMap; import java.util.Map; @Data //@ApiModel(value="全局统一返回结果") public class R { //@ApiModelProperty(value = "是否成功") private Boolean success; //@ApiModelProperty(value = "返回码") private Integer code; //@ApiModelProperty(value = "返回消息") private String message; //@ApiModelProperty(value = "返回数据") private Mapdata = new HashMap (); private R(){} public static R ok(){ R r = new R(); r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess()); r.setCode(ResultCodeEnum.SUCCESS.getCode()); r.setMessage(ResultCodeEnum.SUCCESS.getMessage()); return r; } public static R error(){ R r = new R(); r.setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess()); r.setCode(ResultCodeEnum.UNKNOWN_REASON.getCode()); r.setMessage(ResultCodeEnum.UNKNOWN_REASON.getMessage()); return r; } public R data(Map map){ this.setData(map); return this; } public R data(String key, Object value){ this.data.put(key, value); return this; } public R message(String message){ this.setMessage(message); return this; } public R code(Integer code){ this.setCode(code); return this; } public R success(Boolean success){ this.setSuccess(success); return this; } public static R setResult(ResultCodeEnum resultCodeEnum){ R r = new R(); r.setSuccess(resultCodeEnum.getSuccess()); r.setCode(resultCodeEnum.getCode()); r.setMessage(resultCodeEnum.getMessage()); return r; } }
结果枚举常量类ResultCodeEnum↓
package com.ywj.constants; import lombok.Getter; @Getter public enum ResultCodeEnum { SUCCESS(true, 20000,"成功"), UNKNOWN_REASON(false, 20001, "未知错误"), BAD_SQL_GRAMMAR(false, 21001, "sql语法错误"), JSON_PARSE_ERROR(false, 21002, "json解析异常"), PARAM_ERROR(false, 21003, "参数不正确"), FILE_UPLOAD_ERROR(false, 21004, "文件上传错误"), EXCEL_DATA_IMPORT_ERROR(false, 21005, "Excel数据导入错误"), MY_ERROR(false, 21006, "算术异常错误"); private Boolean success;//响应是否成功 private Integer code;//返回码 private String message;//返回消息 ResultCodeEnum(Boolean success, Integer code, String message) { this.success = success; this.code = code; this.message = message; } }
异常栈信息输出工具类ExceptionUtil↓
package com.ywj.util; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; public class ExceptionUtil { public static String getMessage(Exception e) { StringWriter sw = null; PrintWriter pw = null; try { sw = new StringWriter(); pw = new PrintWriter(sw); // 将出错的栈信息输出到printWriter中 e.printStackTrace(pw); pw.flush(); sw.flush(); } finally { if (sw != null) { try { sw.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (pw != null) { pw.close(); } } return sw.toString(); } }
上面只是解释说明一下,直接拷贝资料文件夹的相关类到公司包即可,比如拷贝到ywj包下,项目结构如下↓
统一日志输出
配置日志级别↓
日志记录器(Logger)的行为是分等级的。如下表所示:
分为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
默认情况下,spring boot从控制台打印出来的日志级别只有INFO及以上级别,可以配置日志级别↓
# 设置日志级别 logging.level.root=WARN
以上方式只能将日志打印在控制台上 ↑
Logback日志↓
spring boot内部使用Logback作为日志实现的框架。
Logback和log4j非常相似,如果你对log4j很熟悉,那对logback很快就会得心应手。
配置logback日志↓
删除application.properties中的日志配置
安装idea彩色日志插件:grep-console
resources 中创建 logback-spring.xml
logback INFO ${CONSOLE_LOG_PATTERN} UTF-8 ${log.path}/log_info.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log 100MB 15 INFO ACCEPT DENY ${log.path}/log_warn.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log 100MB 15 warn ACCEPT DENY ${log.path}/log_error.log %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n UTF-8 ${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log 100MB 15 ERROR ACCEPT DENY
最后,别忘了,在application.yml配置文件中用profiles激活dev开发环境或其他环境比如生产环境pro等↓
server: port: 8888 spring: mvc: view: prefix: /WEB-INF/jsp/ suffix: .jsp profiles: active: dev #logging: # level: # root: warn
复制粘贴即可
其实,上面都只是解释一下,不想太麻烦,直接拷贝资料文件夹的里面的相关类和日志配置文件到项目中即可↑↓
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。