【问题标题】:Spring @ControllerAdvice messageSource doesn't work with Hibernate message parametersSpring @ControllerAdvice messageSource 不适用于 Hibernate 消息参数
【发布时间】:2018-09-01 06:39:30
【问题描述】:

我正在尝试在 Spring Boot REST 控制器中添加一些自定义 bean 验证,使用 @ControllerAdvice 注释扩展 ResponseEntityExceptionHandler 类并覆盖 #handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) 方法。在这种方法中,我试图通过messageSource 将给定的FieldError 转换为本地化消息。虽然我在尝试使用可以通过 Hibernate 验证器实现的消息参数时收到NumberFormatException

我正在使用以下依赖项:

  • org.hibernate.validator:hibernate-validator (6.0.11.Final)
  • org.springframework:spring-web (5.0.8.RELEASE)
  • org.springframework:spring-webmvc (5.0.8.RELEASE)

通过org.springframework.boot:spring-boot-starter-web (2.0.4.RELEASE) 包含所有内容。

考虑使用以下 REST 控制器:

@RestController
public class FooController {

    @PostMapping(value = "/foo")
    public void submitFooRequest(@Validated @RequestBody FooRequest fooRequest) {
        // ....
    }
}

FooRequest bean 有一个自定义 bean 验证注解和约束验证器:

bean FooRequest:

@Getter
@Setter
@ValidBarRequest
public class FooRequest {

    private String fieldFoo;
    private BarRequest barRequest;
}

bean BarRequest:

@Getter
@Setter
public class BarRequest {

    private String fieldBar;
}

验证注解:

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = BarRequestValidator.class)
@Documented
public @interface ValidBarRequest {

    String message() default "{org.example.validation.constraints.ValidBarRequest.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String fieldFoo() default "fieldFoo";

    String barRequestFieldBar() default "barRequest.fieldBar";
}

验证约束验证器:

@Log4j2
public class BarRequestValidator implements ConstraintValidator<ValidBarRequest, Object> {

    // ....

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (/* some condition */) {
            HibernateConstraintValidatorContext hibernateValidatorContext = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
            hibernateValidatorContext.disableDefaultConstraintViolation();
            hibernateValidatorContext.addMessageParameter("fieldFoo", "some value...").buildConstraintViolationWithTemplate("{org.example.validation.constraints.ValidBarRequest.message}")
                .addPropertyNode("barRequest.fieldBar").addConstraintViolation();
            return false;
        }

        return true;
    }
}

但是,通过 @ControllerAdvice 注释的 bean 并使用 Spring messageSource 会在以下消息上引发 NumberFormatException(在 messages.properties 中):

ValidBarRequest.fooRequest.barRequest.fieldBar=must be lower or equal than {fieldFoo}

@ControllerAdvice bean:

@ControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired private MessageSource messageSource;

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException e, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<ErrorDetails> errorDetails = new ArrayList<>();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorDetails.add(new ErrorDetails(fieldError.getField(), messageSource.getMessage(fieldError, Locale.getDefault())));
        }

        return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
    }

    @Getter
    @AllArgsConstructor
    class ErrorDetails {

        private String field;
        private String message;
    }
}

这会导致以下异常:Caused by: java.lang.NumberFormatException: For input string: "fieldFoo"

我做错了什么?我还在我的@SpringBootApplication 中加入了以下 bean:

@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
    LocalValidatorFactoryBean localValidatorFactory = new LocalValidatorFactoryBean();
    localValidatorFactory.setValidationMessageSource(messageSource);

    return localValidatorFactory;
}

【问题讨论】:

    标签: spring-mvc spring-boot hibernate-validator


    【解决方案1】:

    在消息源 MessageFormat.format 中填充变量,您必须在大括号中使用数字。

    ValidBarRequest.fooRequest.barRequest.fieldBar=must be lower or equal than {0}
    

    【讨论】:

    猜你喜欢
    • 2015-09-27
    • 2016-01-01
    • 1970-01-01
    • 2012-10-30
    • 2012-11-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多