Spring Data REST:自定义方法验证

时间:2016-10-24 13:17:08

标签: java spring validation spring-mvc spring-data-rest

我尝试使用带有Spring Data REST注释的@RepositoryRestResource个存储库以及自定义方法实现。 有两种情况:

1)我有一个用@RepositoryRestResource注释的REST存储库,它被映射到/users端点。此外,我有@RestController映射到同一端点。 这会导致@RepositoryRestResource中的方法(应该公开)不可见并获得405结果。然而@Valid注释的方法验证正在{{1 }} 方法。例如这有效:

@RestController

2)与REST存储库一起工作的控制器是@ResponseBody @RequestMapping(value = "/users") public ResponseEntity signUp(@RequestBody @Valid final UserSignUpRequest userSignUpRequest) 个控制器。这样,@RepositoryRestController@RepositoryRestController中声明的两种方法都可以正常工作。但是 JSR-303 @RepositoryRestResource注释方法已停止工作,因此我无法使用@Valid注释。此问题已在DATAREST-593中说明。

任何想法如何解决两个问题中的至少一个?主要思想是将@Valid存储库与自定义控制器方法和注释验证结合使用。

2 个答案:

答案 0 :(得分:4)

你也可以将它添加到你的@RepositoryRestController:

@Inject
private LocalValidatorFactoryBean validator;

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

答案 1 :(得分:1)

在这种情况下似乎没有好的解决方案,默认情况下不支持@Valid注释,请参阅DATAREST-593。为什么,为了支持@Valid方法上的@RepositoryRestController注释,我创建了以下@ControllerAdvice类:

package com.tivoli.api.application.advice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import javax.validation.Valid;
import javax.validation.ValidationException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * Workaround class for making JSR-303 annotation validation work for controller method parameters.
 * Check the issue <a href="https://jira.spring.io/browse/DATAREST-593">DATAREST-593</a>
 */
@ControllerAdvice
public class RequestBodyValidationProcessor extends RequestBodyAdviceAdapter {

    private final Validator validator;

    public RequestBodyValidationProcessor(@Autowired final Validator validator) {
        this.validator = validator;
    }

    @Override
    public boolean supports(final MethodParameter methodParameter, final Type targetType, final Class<? extends
            HttpMessageConverter<?>> converterType) {
        final Annotation[] parameterAnnotations = methodParameter.getParameterAnnotations();
        for (final Annotation annotation : parameterAnnotations) {
            if (annotation.annotationType().equals(Valid.class)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Object afterBodyRead(final Object body, final HttpInputMessage inputMessage, final MethodParameter
            parameter, final Type targetType, final Class<? extends HttpMessageConverter<?>> converterType) {
        final Object obj = super.afterBodyRead(body, inputMessage, parameter, targetType, converterType);
        final BindingResult bindingResult = new BeanPropertyBindingResult(obj, obj.getClass().getCanonicalName());
        validator.validate(obj, bindingResult);
        if (bindingResult.hasErrors()) {
            throw new ValidationException(createErrorMessage(bindingResult));
        }

        return obj;
    }

    private String createErrorMessage(final BindingResult bindingResult) {
        final StringBuilder stringBuilder = new StringBuilder("Invalid parameters specified.");
        if (bindingResult.getFieldErrors() != null && !bindingResult.getFieldErrors().isEmpty()) {
            stringBuilder.append(" Fields:");
            bindingResult.getFieldErrors().forEach(fieldError -> stringBuilder
                    .append(" [ ")
                    .append(fieldError.getField())
                    .append(" : ")
                    .append(fieldError.getRejectedValue())
                    .append(" ] "));
        } else if (bindingResult.getAllErrors() != null && !bindingResult.getAllErrors().isEmpty()) {
            final ObjectError objectError = bindingResult.getAllErrors().get(0); // get the first error
            stringBuilder.append(" Message: ")
                    .append(objectError.getDefaultMessage());
        }

        return stringBuilder.toString();
    }
}