Validation

默认情况下,如果 Bean Validation 存在于类路径(例如,Hibernate Validator),那么 LocalValidatorFactoryBean 将被注册为全局 Validator,用于 @Valid@Validated 中的控制器方法参数。

By default, if Bean Validation is present on the classpath (for example, Hibernate Validator), the LocalValidatorFactoryBean is registered as a global Validator for use with @Valid and @Validated on controller method arguments.

你可以自定义全局 Validator 实例,如下例所示:

You can customize the global Validator instance, as the following example shows:

  • Java

  • Kotlin

  • Xml

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

	@Override
	public Validator getValidator() {
		Validator validator = new OptionalValidatorFactoryBean();
		// ...
		return validator;
	}
}
@Configuration
class WebConfiguration : WebMvcConfigurer {

	override fun getValidator(): Validator {
		val validator = OptionalValidatorFactoryBean()
		// ...
		return validator
	}
}
<mvc:annotation-driven validator="globalValidator"/>

请注意,你还可以注册本地 Validator 实现,如下例所示:

Note that you can also register Validator implementations locally, as the following example shows:

  • Java

  • Kotlin

@Controller
public class MyController {

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.addValidators(new FooValidator());
	}
}
@Controller
class MyController {

	@InitBinder
	fun initBinder(binder: WebDataBinder) {
		binder.addValidators(FooValidator())
	}
}

如果你需要在某处注入 LocalValidatorFactoryBean,请创建一个 Bean,然后用 @Primary 标记它,以避免与在 MVC 配置中声明的 Bean 产生冲突。

If you need to have a LocalValidatorFactoryBean injected somewhere, create a bean and mark it with @Primary in order to avoid conflict with the one declared in the MVC configuration.