|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
验证
默认情况下,如果类路径中存在Bean Validation(例如 Hibernate Validator),则会注册LocalValidatorFactoryBean作为全局Validator,用于在控制器方法参数上使用@Valid和Validated。
在 Java 配置中,您可以自定义全局的 Validator 实例,如下例所示:
-
Java
-
Kotlin
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public Validator getValidator() {
// ...
}
}
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
override fun getValidator(): Validator {
// ...
}
}
以下示例展示了如何在 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/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实现:
-
Java
-
Kotlin
@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 配置中声明的 bean 发生冲突。 |