I have an object like so:
public class Foo {
public interface FooValidator{};
@Null(groups = {FooValidator.class}, message = "Id is null!!!")
private Integer id;
@NotEmpty(message = "Description is empty")
private String description;
}
And a controller like so:
public class FooController {
@PutMapping(value = "/{actionItemId}")
public ResponseEntity bar1(@Validated({Foo.FooValidator.class}) @RequestBody Foo foo) {
//stuff
}
@PostMapping
public ResponseEntity bar2(@Validated @RequestBody Foo foo) {
//stuff
}
}
My problem is for the bar1
method, it's only validating the id
field and not the description field. But the bar2
method is working fine, it's validating the description field and not the id field.
How do I get spring's @Validated
annotation to validate fields with the appropriate interface annotation AND all the other normal fields (one's without annotation.
In other words, how do i get the bar1
method to validate both the id
and the description
fields?
@Validated
annotation should be used on class level. It is used to say that inside the class some validation is performed. Meaning that it works with other validation annotation which will be applied to properties, parameters etc. I am posting an example from the documentation:
@Service
@Validated
public class MyBean {
public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code,
Author author) {
...
}
}
If you want to validate a custom class, as it seems to me from the example, you should instead use the @Valid
annotation which will apply validation to the properties of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With