如何优雅的写 Controller 层代码?
后端思想篇:设计好接口的36个锦囊!
瞧瞧,人家这后端API接口写得,那叫一个巴适~,再看看我的,像坨屎!
实战总结!18种接口优化方案的总结
SpringBoot 还在用 if 校验参数?那你真的太low了,老司机都是这么玩的!
7种方式,教你提升 SpringBoot 项目的吞吐量
Spring Boot 程序优化的 14 个小妙招!
统一返回格式
定义一个业务CODE枚举类
public enum ResultCodeEnum {SUCCESS(1, "成功"),//参数错误ILLEGAL_PARAMETER(10001, "非法参数");private Integer code;private String msg;ResultCodeEnum(Integer code, String msg) {this.code = code;this.msg = msg;}public Integer getCode() {return code;}public String getMsg() {return msg;}
}
定义统一返回类
public class R<T> implements Serializable {private T data;private Integer code;private String msg;public static <T> R<T> ok(T data) {R<T> r = new R<>();r.setData(data);return r;}public static <T> R<T> ok(ResultCodeEnum codeEnum, T data) {R<T> r = new R<>();r.setData(data);r.setCode(codeEnum.getCode());r.setMsg(codeEnum.getMsg());return r;}public static <T> R<T> fail(Integer code, String msg) {R<T> r = new R<>();r.setCode(code);r.setMsg(msg);return r;}public static <T> R<T> fail(ResultCodeEnum codeEnum) {R<T> r = new R<>();r.setCode(codeEnum.getCode());r.setMsg(codeEnum.getMsg());return r;}//省略部分代码
}
定义一个封装注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface Result {
}
ResponseBodyAdvice
Allows customizing the response after the execution of an @ResponseBody or a ResponseEntity controller method but before the body is written with an HttpMessageConverter.
两种思路,一种是beforeBodyWrite,另一种是 String
全局异常处理
@RestControllerAdvice
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ControllerAdvice
@ResponseBody
public @interface RestControllerAdvice {@AliasFor(annotation = ControllerAdvice.class)String[] value() default {};@AliasFor(annotation = ControllerAdvice.class)String[] basePackages() default {};@AliasFor(annotation = ControllerAdvice.class)Class<?>[] basePackageClasses() default {};@AliasFor(annotation = ControllerAdvice.class)Class<?>[] assignableTypes() default {};@AliasFor(annotation = ControllerAdvice.class)Class<? extends Annotation>[] annotations() default {};
}
@ExceptionHandler
//修饰方法
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {//接收一个Throwable子类的class数组Class<? extends Throwable>[] value() default {};
}
@ExceptionHandler(MethodArgumentNotValidException.class)