问题描述
假设我有一个这样的示例实体类:
Suppose I have a sample entity class like this:
public class Address {
...
}
和相应的验证器:
@Component
public AddressValidator implements Validator {
@Override
public boolean supports(Class<?> entityClass) {
return entityClass.equals(Address.class);
}
@Override
public void validate(Object obj, Errors errors) {
...
}
}
当我使用如下所示的控制器时,一切正常:
When I use a controller like the following, everything works:
@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) {
...
}
}
但是,如果我省略了验证器注册部分(即以下内容),则不会执行验证.
However, if I omit the validator registering part (i.e. the following), validation is not performed.
@Autowired
private AddressValidator validator;
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
必须手动注册验证器似乎毫无意义.我可以指示Spring自动查找验证器(类似于查找控制器的方式)吗?
Having to register validators manually seems pointless. Can I instruct Spring to look up validators automatically (similar to how controllers are looked up)?
这是一个基于Spring Boot的应用程序.
It's a Spring Boot based application.
推荐答案
您可以从要点或以下.这个想法是要有一个主要的CompositeValidator,它将成为您所有Validator或SmartValidator实例的所有者.
You can use my example from gist or below. The idea is to have a main CompositeValidator that will be a holder of all your Validator or SmartValidator instances.
它支持提示,还可以与Hibernate Annotation Validator(LocalValidatorFactoryBean)集成.每个特定模型也可能有一个以上的验证器.
It supports hints and can be also integrate with Hibernate Annotation Validator (LocalValidatorFactoryBean). And also it's possible to have more that one validator per specific Model.
CompositeValidator.java
@Component
public class CompositeValidator implements SmartValidator {
@Autowired
private List<Validator> validators = Collections.emptyList();
@PostConstruct
public void init() {
Collections.sort(validators, AnnotationAwareOrderComparator.INSTANCE);
}
@Override
public boolean supports(Class<?> clazz) {
for (Validator validator : validators) {
if (validator.supports(clazz)) {
return true;
}
}
return false;
}
@Override
public void validate(Object target, Errors errors) {
validate(target, errors, javax.validation.groups.Default.class);
}
@Override
public void validate(Object target, Errors errors, Object... validationHints) {
Class<?> clazz = target.getClass();
for (Validator validator : validators) {
if (validator.supports(clazz)) {
if (validator instanceof SmartValidator) {
((SmartValidator) validator).validate(target, errors, validationHints);
} else {
validator.validate(target, errors);
}
}
}
}
}
SomeController.java
@Controller
@RequestMapping("/my/resources")
public class SomeController {
@RequestMapping(method = RequestMethod.POST)
public Object save(
@Validated(javax.validation.groups.Default.class) // this interface descriptor (class) is used by default
@RequestBody MyResource myResource
) { return null; }
}
Java配置
@Configuration
public class WebConfig {
/** used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy */
// @Bean
// public Validator jsr303Validator() {
// LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
// // validator.setValidationMessageSource(...);
// return validator;
// }
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
return new WebMvcConfigurerAdapter() {
@Autowired
private CompositeValidator validator;
@Override
public Validator getValidator() {
return validator;
}
}
}
或XML配置
<!-- used for Annotation based validation, it can be created by spring automaticaly and you don't do it manualy -->
<!--<bean id="jsr303Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">-->
<!-- <property name="validationMessageSource" ref="messageSource"/>-->
<!--</bean>-->
<mvc:annotation-driven validator="compositeValidator">
//...
</mvc:annotation-driven>
这篇关于Spring MVC-自动查找验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!