这里列出我最终解决方法,详细的解决原理我整理一下再发。
最终配置方案:
<!-- 由于 annotation-driven 会自动创建RequestMappingHandlerAdapter,故这里注释掉--> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <!--将验证器注入webBinder--> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <property name="validator" ref="validator"></property> </bean> </property> </bean> --> <!--验证器--> <mvc:annotation-driven validator="validator"/> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> </bean>
代码:
@Controller public class MyControllerImpl { @RequestMapping(method = RequestMethod.POST) @ResponseBody public String save(@Validated({AddGroup.class}) User entity) { System.out.println("验证"); return "ok"; } }
// User.class public class User implements Serializable { /** * 主键 */ @Id @Column(name = "user_id") @NotEmpty(message = "主键不能为空", groups = {AddGroup.class}) private String userId; /** * 用户名 */ @NotEmpty(message = "用户名不能为空", groups = {AddGroup.class}) private String username; }
// AddGroup.class public interface AddGroup { }
/** * MyExceptionHandler.class * 异常处理 */ @RestControllerAdvice("org.tingwen") public class MyExceptionHandler { @ExceptionHandler(BindException.class) public Result handleBindException(BindException e) { Map<String, String> data = new HashMap<>(); for (ObjectError error : e.getAllErrors()) { data.put(((FieldError) error).getField(), error.getDefaultMessage()); } Result r = new Result(); r.setMessage(Message.CHECK_ERROR); r.setData(data); return r; } }
结果
//发送 post 请求 http://localhost:8080/user
//返回值 { "code": -105, "data": { "userId": "主键不能为空", "username": "用户名不能为空" }, "msg": "校验错误" }