【发布时间】:2017-04-13 22:08:08
【问题描述】:
我有自定义验证器并在我的控制器中注册它
@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 是如何理解我想要创建全局验证器的呢?扫描每个实现的 Validator 类?我可以用xml配置来做吗?如何使用这种方法?
我看不懂Spring的描述:
另一种方法是在全局上调用 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=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xss http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven validator="globalValidator"/>
【问题讨论】:
-
验证器名为
globalValidator...或者名为fooBar的验证器,如果你写<mvc:annotation-driven validator="fooBar"/> -
所以“globalValidator”只是之前创建的验证器的名称?那么,如果 Iwan 将其中两个放到全球范围内呢?
-
你不能......你只能有一个全局验证器......
标签: java spring validation spring-mvc