Spring MVC总是将@Valid应用于特定参数对象

时间:2016-12-16 17:18:26

标签: java spring spring-mvc

假设我想验证所有RESTful方法(> 50)的传入ID参数。

作为一个例子,我有:

@RequestMapping(
        value = "/{id}",
        method = RequestMethod.GET,
        produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Metadata getMetadata(
        @PathVariable("id") Long id,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    return metadataService.get(id);
}

我想拒绝所有请求,如果id< 1.作为我实施的解决方案:

@RequestMapping(
        value = "/{id}",
        method = RequestMethod.GET,
        produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
Metadata getMetadata(
        @Valid Id id,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    return metadataService.get(id.asLong());
}

public class Id {

@Min(1)
@NotNull
private Long id;

public void setId(Long id) {
    this.id = id;
}

public Long asLong() {
    return id;
}

}

但是现在我必须隐含地为Id参数的每个方法添加@Valid注释,这似乎是多余的。有没有办法告诉Spring,如果有一个Id对象作为传入参数,它应该总是@Valid。没有每次都注释?

感谢。

1 个答案:

答案 0 :(得分:0)

所以我最终得到了这样的解决方案:

public class CustomModelAttributeMethodProcessor extends ModelAttributeMethodProcessor {

public CustomModelAttributeMethodProcessor(boolean annotationNotRequired) {
    super(annotationNotRequired);
}

@Override
protected void bindRequestParameters(final WebDataBinder binder, final NativeWebRequest request) {
    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    ((ServletRequestDataBinder) binder).bind(servletRequest);
}

@Override
protected void validateIfApplicable(final WebDataBinder binder, final MethodParameter parameter) {
    if (binder.getTarget().getClass().equals(Id.class)) {
        binder.validate();
        return;
    }

    super.validateIfApplicable(binder, parameter);
}

}

配置:

@Configuration
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new CustomModelAttributeMethodProcessor(true));
    }
}

检查每个传入参数的类有点开销,但按预期工作。现在可以省略@Valid注释,因为验证由自定义处理器执行。