springboot validation 检验模式


springboot validation 检验模式

 

默认:对pojo的所有参数进行检验,如果检验出错,返回所有错误

fail-fast:检验到参数出错就返回当前错误,不需要检验所有的参数

 

 

*************************

示例

 

*******************

pojo 层

 

Order

@Data
public class Order {

    @FutureOrPresent(message = "时间不能为过去时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime orderTime;

    @DecimalMin(value = "0.01",message = "最小值为0.01")
    private Double price;

    @Min(value = 1,message = "最小值为1")
    private Integer amount;
}

 

*******************

config 层

 

WebConfig

@Configuration
public class WebConfig {

    @Bean
    public Validator initValidator(){
        return Validation.byProvider(HibernateValidator.class)
                .configure().failFast(true)
                .buildValidatorFactory()
                .getValidator();
    }
}

 

*******************

controller 层

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(@Validated Order order,BindingResult result){
        System.out.println(order);

        if (result.hasFieldErrors()){
            result.getFieldErrors().forEach(error -> {
                System.out.print("field:"+error.getField());
                System.out.println(" ==> defaultMessage:"+error.getDefaultMessage());
            });
        }

        return "success";
    }
}

 

 

*************************

使用测试:localhost:8080/hello?orderTime=2020-01-02 09:00:08&price=2&amount=0

 

默认检验输出

2020-07-14 09:55:14.749  INFO 14772 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-14 09:55:14.757  INFO 14772 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
Order(orderTime=2020-01-02T09:00:08, price=2.0, amount=0)
field:orderTime ==> defaultMessage:时间不能为过去时间
field:amount ==> defaultMessage:最小值为1

默认检验所有参数,将所有错误一起输出

 

fail-fast输出

2020-07-14 09:48:31.746  INFO 9408 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-07-14 09:48:31.761  INFO 9408 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 15 ms
Order(orderTime=2020-01-02T09:00:08, price=2.0, amount=0)
field:amount ==> defaultMessage:最小值为1

fail-fast检验出错,就将错误输出,立即返回

 

 


版权声明:本文为weixin_43931625原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。