<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
groovy
implementation 'org.springframework.boot:spring-boot-starter-validation'
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class User {
private String username;
private String password;
}
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
public class UserController {
@PostMapping("/users")
public String createUser(@Valid @RequestBody User user) {
return "User created successfully";
}
}
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
return ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
}
}