sharp-common集成Spring Web

sharp-common 集成Spring Web主要体现在以下3个方面

  • 通过注解 @RestControllerAdvice 封装异常异常 ApiExceptionHandler
  • 注入国际化的工具类 MessageUtils
  • 封装 Result 返回对象

集成

  • 添加包扫描,将 ApiExceptionHandlerMessageUtils纳入Spring上下文,@EnableResultWrapped 自动包裹 Result 对象。
  1. @Configuration
  2. @Import({ApiExceptionHandler.class, MessageUtils.class})
  3. @EnableResultWrapped
  4. public class MvcConfig implements WebMvcConfigurer {}
  • 国际化文件
# messages_en_US.properties
BEAN_VALIDATE_ERROR=Params validate error:{0}
MAX_TRY_LOGIN_ERROR=The account failed to log in {0} times, please wait {1} minutes and try again

# messages_zh_CN.properties
BEAN_VALIDATE_ERROR=参数验证错误:{0}
MAX_TRY_LOGIN_ERROR=该账号{0}次登录失败后,被锁定{1}分钟
  • 添加业务异常枚举
  1. @Getter
  2. @ToString
  3. public enum ExceptionCode {
  4. BEAN_VALIDATE_ERROR(30002, "BEAN_VALIDATE_ERROR"),
  5. PRICE_CRAWLER_ERROR(40004, "网站价格获取失败");
  6. private int code;
  7. private String msg;
  8. ExceptionCode(int code, String msg) {
  9. this.code = code;
  10. this.msg = msg;
  11. }
  12. public ExceptionResult<String> result() {
  13. return new ExceptionResult<>(getCode(), getMsg());
  14. }
  15. }

BEAN_VALIDATE_ERROR 在国际化文件中进行了语言维护。

测试

  1. @RestController
  2. @RequestMapping("test")
  3. public class TestController {
  4. @GetMapping("1")
  5. public Result test1() {
  6. return ResultUtils.success(MessageUtils.getMessage("MAX_TRY_LOGIN_ERROR", new Object[] {5, 20}));
  7. }
  8. @GetMapping("2")
  9. public Result test2() {
  10. int a = 1 / 0;
  11. return ResultUtils.success();
  12. }
  13. @GetMapping("3")
  14. public Result test3() {
  15. return ResultUtils.fail();
  16. }
  17. @GetMapping("4")
  18. public Result test4() {
  19. throw new BizException(ExceptionCode.FORMULA_ERROR.result());
  20. }
  21. @GetMapping("5")
  22. public Result test5() {
  23. throw new BizException(ExceptionCode.BEAN_VALIDATE_ERROR.result(), new Object[] {"姓名不能为空"});
  24. }
  25. @GetMapping("6")
  26. public int test5() {
  27. return 1
  28. }
  29. @GetMapping("7")
  30. @UnWrapped
  31. public int test7() {
  32. return 7
  33. }
  34. }

注解 @UnWrapped 表示不需要被 Result 对象包裹。