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的应用程序.
您可以配置全局验证器。
如果您将基于 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)
| 归档时间: |
|
| 查看次数: |
3545 次 |
| 最近记录: |