1

I'm learning java and spring boot and I am trying to validate a controller parameter which was bound from json.

I've got simple Entity:

@Getter
@Setter
class Resource {
    @NotBlank
    String uri;
}

Which I want to persist through the following controller:

@BasePathAwareController
public class JavaResourcePostController {

    private final ResourceRepository repository;

    public JavaResourcePostController(ResourceRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(value = "/resources", method = RequestMethod.POST)
    ResponseEntity<Resource> create(
        @Valid @RequestBody Resource resource
    ) {
        repository.save(resource);

        return ResponseEntity.ok(resource);
    }
}

My understanding is that the resource argument should be valid when entering the method. But posting an empty uri field does not trigger the validation of the method. it does however get triggered in the hibernate validation in repository.save()

Why does the @Valid annotation on the argument not ensure I get a validated entity?

NDM
  • 6,731
  • 3
  • 39
  • 52
  • 3
    Try adding `@Validated`to your controller. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html – geobreze Dec 13 '21 at 20:39
  • This works when I annotation `@Validated` on the class level idd! I only tried this on the argument and method. can you post this as an answer, so this can be accepted and closed? – NDM Dec 13 '21 at 20:51

1 Answers1

4

You need to add @Validated to your controller class.

geobreze
  • 2,274
  • 1
  • 10
  • 15
  • This idd solved the issue, any idea why this doesnt work in kotlin, only in java? – NDM Dec 13 '21 at 23:13
  • to get it working in kotlin I also needed to add the spring plugin to the kotlin maven plugin as answered here: https://stackoverflow.com/questions/52345291/bean-validation-not-working-with-kotlin-jsr-380 – NDM Dec 13 '21 at 23:38