@Data
public class Employee{
@NotNull
@NotBlank
private string id;
@NotNull
@NotBlank
private string name;
}
@RestController
@Validated
class EmployeeController{
@postMapping(consumes="json", produces="json")
public ResponseEntity getEmployee(@Valid @RequestBody Employee){
return response;
}
}
Added Exceptional Handler with MethodArgumentNotvalidException.
positive Validation works fine, Whenever we check with id & name.
Expectation is, if we add any additional parameters along with id and name, it should throw the 400
sample input : { "abc":"xyz", "id":"09e240", "name":"Billa" }
Expected Output : 400 bad request
The validation doesn't occur until after the deserialization into the
Employee
object has occurred; therefore, I don't believe you can do this with the validation API.What you want to do is force the deserialization to fail on unknown properties. Create a bean of type
ObjectMapper
and configure it to fail deserialization when it encounters unknown properties.This will throw an
UnrecognizedPropertyException
, then you can use ControllerAdvice to map this to a 400. By the way, I suspect that you have already created this bean somewhere as the default behavior for ObjectMapper is set to FAIL_ON_UNKNOWN_PROPERTIES -> true.The controller advice to map the
UnrecognizedPropertyException
will look like this: