java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot校验注解

解析SpringBoot自定义参数校验注解

作者:闪耀的瞬间

这篇文章主要介绍了SpringBoot自定义参数校验注解,引入依赖,spring validation是在hibernate-validator上做了一层封装,文中提到了定义参数校验注解与处理器的示例代码,感兴趣的朋友跟随小编一起看看吧

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进来
    @Autowired
    private OrderService orderService;
    @Override
    public boolean isValid(Integer buyCount, ConstraintValidatorContext context) {
        return orderService.OrderCountValid(buyCount);
    }
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class OrderCountValidator implements ConstraintValidator<OrderCountValid , Integer> {
    //可以注入mapper、service进来
    @Autowired
    private OrderService orderService;
    @Override
    public boolean isValid(Integer buyCount, ConstraintValidatorContext context) {
        return orderService.OrderCountValid(buyCount);
    }
}

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 "请求参数错误";
    }
}

到此这篇关于SpringBoot自定义参数校验注解的文章就介绍到这了,更多相关SpringBoot校验注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文