Spring MVC - 自动查找验证器

Duš*_*ský 9 java validation spring spring-mvc

假设我有一个像这样的示例实体类:

public class Address {
    ...
}
Run Code Online (Sandbox Code Playgroud)

和相应的验证器:

@Component
public AddressValidator implements Validator {

    @Override
    public boolean supports(Class<?> entityClass) {
        return entityClass.equals(Address.class);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用如下控制器时,一切正常:

@RestController
@RequestMapping("/addresses")
public class AddressController {

    @Autowired
    private AddressValidator validator;

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

    @RequestMapping(method=POST)
    public Long addNewAddress(@Valid @RequestBody Address address) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果省略验证器注册部分(即以下内容),则不执行验证.

@Autowired
private AddressValidator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}
Run Code Online (Sandbox Code Playgroud)

必须手动注册验证器似乎毫无意义.我可以指示Spring自动查找验证器(类似于控制器的查找方式)吗?

这是一个基于Spring Boot的应用程序.

mav*_*azy 1

您可以配置全局验证器。

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#validation-mvc

如果您将基于 Java 的 spring 配置与 WebMvcConfigurationSupport 一起使用,则可以覆盖 getValidator()

/**
 * Override this method to provide a custom {@link Validator}.
 */
protected Validator getValidator() {
    return null;
}
Run Code Online (Sandbox Code Playgroud)

您可以在全局 WebBindingInitializer 上调用 setValidator(Validator)。这允许您跨所有 @Controller 类配置 Validator 实例。这可以通过使用 Spring MVC 命名空间轻松实现:

<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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

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

</beans>
Run Code Online (Sandbox Code Playgroud)

  • 您只能注册一个全局验证器,对吗?当参数标记为 @Valid 时,您如何告诉 spring 加载多个验证器并选择要使用的正确实现? (2认同)