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

验证

默认情况下,如果存在 Bean Validation 在 Classpath(例如,Hibernate Validator)上,LocalValidatorFactoryBean是 注册为全局验证器以用于@ValidValidatedon controller 方法参数。spring-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 配置中声明的冲突。