Java “理解”;globalValidator“;春季MVC

Java “理解”;globalValidator“;春季MVC,java,spring,validation,spring-mvc,Java,Spring,Validation,Spring Mvc,我有自定义验证器,并在控制器中注册它 @Controller public class MyController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new FooValidator()); } @RequestMapping("/foo", method=RequestMethod.POST) publi

我有自定义验证器,并在控制器中注册它

@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new FooValidator());
    }

    @RequestMapping("/foo", method=RequestMethod.POST)
    public void processFoo(@Valid Foo foo) { ... }

}
但我也想在其他控制器中注册,以便能够只写@Valid和要验证的Foo对象。据我所知,我可以使用@ControllerAdviced类在每个控制器上注册验证器,或者使用

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

但是如何注册我的验证器,Spring如何理解我想创建全局验证器?扫描每个实现的验证程序类?我可以用xml配置来完成吗?如何使用这种方法

我不理解弹簧的描述:

另一种方法是在全局服务器上调用setValidator(Validator) WebBindingInitializer。此方法允许您配置 跨所有带注释的控制器的验证程序实例。这可能是 通过使用SpringMVC命名空间实现:

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=” “>


文档在以下方面非常清晰:

在SpringMVC中,您可以将其配置为用作全局验证器 实例,当@Valid或@Validated控制器 方法参数在一个 控制器通过@InitBinder方法执行。全局和本地验证器 实例可以组合以提供复合验证

如果我在您的示例中正确理解了FooValidator,那么您希望在每次验证时将其作为全局验证器使用,因此将其定义为bean,并按照您在
mvc:annotation-driven
XML条目中直接显示的方式将其插入

在每个控制器上,您可以通过
@InitBinder
注释进行自定义(仅在该控制器负责表单上应用)

作为旁注,在接收POST请求的
@RequestMapping
方法中,
@Valid
参数为:您可以在该参数之后有一个
BindingResult
条目,以便对路由等做出决定。在您的示例中:

@RequestMapping("/foo", method=RequestMethod.POST)
public String processFoo(@Valid Foo foo, BindingResult result) {

   if(result.hasErrors()) {
      return "go/that/way";
   }
   //..
}

文件在以下方面非常清楚:

在SpringMVC中,您可以将其配置为用作全局验证器 实例,当@Valid或@Validated控制器 方法参数在一个 控制器通过@InitBinder方法执行。全局和本地验证器 实例可以组合以提供复合验证

如果我在您的示例中正确理解了FooValidator,那么您希望在每次验证时将其作为全局验证器使用,因此将其定义为bean,并按照您在
mvc:annotation-driven
XML条目中直接显示的方式将其插入

在每个控制器上,您可以通过
@InitBinder
注释进行自定义(仅在该控制器负责表单上应用)

作为旁注,在接收POST请求的
@RequestMapping
方法中,
@Valid
参数为:您可以在该参数之后有一个
BindingResult
条目,以便对路由等做出决定。在您的示例中:

@RequestMapping("/foo", method=RequestMethod.POST)
public String processFoo(@Valid Foo foo, BindingResult result) {

   if(result.hasErrors()) {
      return "go/that/way";
   }
   //..
}

名为
globalValidator
的验证器。。。或者,如果您编写
,那么名为
fooBar
的验证程序“globalValidator”只是先前创建的验证程序的名称?那么,如果我想把其中两个交给bi global呢?你不能。。您只能有一个全局验证器…名为
globalValidator
的验证器。。。或者,如果您编写
,那么名为
fooBar
的验证程序“globalValidator”只是先前创建的验证程序的名称?那么,如果我想把其中两个交给bi global呢?你不能。。您只能有一个全局验证程序。。。