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())
}
}
如果你需要在某处注入 |
If you need to have a |