默认情况下,如果 Bean Validation 在 classpath 上存在(例如 Hibernate Validator),LocalValidatorFactoryBean 会被注册为全局 Validator,用于@Valid 和 Validated on controller 方法参数。
比如加上 Hibernate Validator 的依赖
implementation 'org.hibernate.validator:hibernate-validator:6.0.0.Final'// 该依赖在 org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator 中有用到,所以需要添加implementation group: 'org.glassfish', name: 'javax.el', version: '3.0.0'
关于缺少依赖包这种,怎么看?最简单的方法是看 中央仓库中对应的页面,在页面中找到 Provided Dependencies
然后就找到对应的包了(当然有些包的作者不会写这个,就没有办法了,只能看报错的地方,缺少是什么依赖,再去找)
@PostMapping("/data")@ResponseBodypublic Pet data(@Valid @RequestBody Pet pet) {System.out.println(pet);return pet;}
package cn.mrcode.study.springdocsread.web;import javax.validation.constraints.NotNull;/*** @author mrcode*/public class Pet {@NotNullprivate String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}
在 Java 配置中,你可以自定义全局验证器实例,如下例所示:
@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {@Overridepublic Validator getValidator() {// ...}}
下面的例子显示了如何在 XML 中实现同样的配置:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd"><mvc:annotation-driven validator="globalValidator"/></beans>
注意,你也可以在本地注册 Validator 实现,如下例所示:
@Controllerpublic class MyController {@InitBinderprotected void initBinder(WebDataBinder binder) {binder.addValidators(new FooValidator());}}
:::tips 如果你需要在某个地方注入一个 LocalValidatorFactoryBean,创建一个 Bean,并用 @Primary 标记,以避免与 MVC 配置中声明的 Bean 发生冲突。 :::
