对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

验证

默认情况下,如果Bean Validation存在于类路径上(例如,Hibernate Validator),则LocalValidatorFactoryBean会被注册为全局验证器,用于控制器方法参数上的@ValidValidatedspring-doc.cadn.net.cn

在Java配置中,你可以自定义全局Validator实例,如下例所示:spring-doc.cadn.net.cn

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	@Override
	public Validator getValidator() {
		// ...
	}
}
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

	override fun getValidator(): Validator {
		// ...
	}
}

以下示例展示了如何在XML中实现相同的配置:spring-doc.cadn.net.cn

<?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/beans
		https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/mvc
		https://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<mvc:annotation-driven validator="globalValidator"/>

</beans>

请注意,您还可以在本地注册 Validator 个实现, 如下例所示:spring-doc.cadn.net.cn

@Controller
public class MyController {

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

	@InitBinder
	protected fun initBinder(binder: WebDataBinder) {
		binder.addValidators(FooValidator())
	}
}
如果你需要在某个地方注入一个LocalValidatorFactoryBean,创建一个bean并用@Primary标记它,以避免与MVC配置中声明的那个发生冲突。