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.
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
return objectMapper;
}
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:
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class Advice {
@ExceptionHandler(UnrecognizedPropertyException.class)
public ResponseEntity<?> handleDeserializationErrors(UnrecognizedPropertyException unrecognizedPropertyException) {
return ResponseEntity.badRequest().body(unrecognizedPropertyException.getMessage());
}
}