1.引入依赖,spring validation是在hibernate-validator上做了一层封装
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
2.定义参数校验注解与处理器
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Constraint(validatedBy = OrderCountValidator.class)
public @interface OrderCountValid {String message() default "订单数量超出库存";Class<?>[] groups() default {};Class<? extends Payload>[] payload() default {};}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;public class OrderCountValidator implements ConstraintValidator<OrderCountValid , Integer> {//可以注入mapper、service进来@Autowiredprivate OrderService orderService;@Overridepublic boolean isValid(Integer buyCount, ConstraintValidatorContext context) {return orderService.OrderCountValid(buyCount);}
}
public class Order implements Serializable {//购买数量@OrderCount(message = "购买数量不能超出库存")@NotNull(message = "购买数量不能为空")private Integer buyCount;//订单编号private String orderCode;
}
3.控制器层
@RestController
@RequestMapping(value = "/order")
public class OrderController {@PostMapping("/placeOrder")public String placeOrder(@RequestBody @Valid Order order){return "success";}
}
4.全局异常处理器,自定义校验注解校验失败会抛出 javax.validation.ConstraintViolationException
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;@RestControllerAdvice
@Component
public class GlobalExceptionHandler {// 当直接校验具体参数时会出现javax.validation.ConstraintViolationException@ExceptionHandler(value = ConstraintViolationException.class)public String handleException1(ConstraintViolationException e) {// 拼接参数String errorMsg = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(", "));return errorMsg;}// 当直接校验具体参数时会出现org.springframework.web.bind@ExceptionHandler(value = MethodArgumentNotValidException.class)public String handleException2(MethodArgumentNotValidException e) {BindingResult exceptions = e.getBindingResult();// 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息if (exceptions.hasErrors()) {// 这里默认错误消息return exceptions.getFieldError().getDefaultMessage();}return "请求参数错误";}
}