Skip to content

Spring MVC and WebFlux docs need to say method validation applies if any method parameter has constraint annotations  #32082

Closed
@dreis2211

Description

@dreis2211

Hi,

when upgrading to Spring-Boot 3.2.2 and therefore SF 6.1.3 we noticed a change in behaviour that causes one of our @ExceptionHandlers not to be triggered anymore, when the @RequestBody fails validation (in this case when Body#target is null).

	@PostMapping(value = "hello", produces = MediaType.TEXT_PLAIN_VALUE)
	public String hello(@RequestBody @Valid @NotNull Body body) {
		return "Hello " + body.target;
	}

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
		System.out.println(ex.getMessage());
		Map<String, String> errors = new HashMap<>();
		ex.getBindingResult().getAllErrors().forEach((error) -> {
			String fieldName = ((FieldError) error).getField();
			String errorMessage = error.getDefaultMessage();
			errors.put(fieldName, errorMessage);
		});
		return errors;
	}

	public static class Body {

		@NotNull
		@Valid
		private String target;

		public Body() {}

		public void setTarget(String target) {
			this.target = target;
		}
	}

Interestingly, this can be worked around by removing the @NotNull from the method parameter.

I think this is somewhat related to #31711 but without the indication that the fix causes the additional annotations not to work anymore or respectively breaking the validation somehow if present.

I've created a minimal reproducer under https://github.com/dreis2211/method-argument-validation-bug to ease testing. Rolling back to SB 3.2.1 fixes it, similar to removing the @NotNull annotation. I'd appreciate if this is either fixed or explicitly documented. Use cases with List request bodies in combination with a @NotEmpty seem to be unaffected because they don't seem to throw a MethodArgumentNotValidException in the first place (also with SB 3.2.1).

In case the @NotNull annotation is not supported under certain circumstances, feel free to turn this into a documentation issue.

Let me know if you need anything.
Cheers,
Christoph

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: documentationA documentation task

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions