Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Mastering Parameter Validation in Spring Boot with Spring Validation

Tech Nov 26 10

Java's JSR 380 (Bean Validation 2.0) defines a standard for validating Java beans, but doesn't include an implementation. Hibernate Validator is a popular implementation that adds annotations like @Email and @Length. Spring Validation builds on top of Hibernate Validator to enable automatic parameter validation in Spring MVC. Below is a comprehensive guide to using Spring Validation in Spring Boot applications.

Basic Usage

Dependency Setup

For Spring Boot versions prior to 2.3.x, the spring-boot-starter-web dependency automatically includes Hibernate Validator. For versions 2.3.x and above, you need to explicitly add the dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.2.0.Final</version>
</dependency>

Web services require parameter validation to prevent invalid input from affecting business logic. Request parameters typically come in two forms:

  1. POST/PUT requests using requestBody to send structured data
  2. GET requests using requestParam or PathVariable for individual parameters

Validating requestBody Parameters

POST/PUT requests often use requestBody to pass complex data, which is received via a DTO (Data Transfer Object) in the backend. Adding validation annotations to the DTO and using @Validated (or @Valid) on the method parameter triggers automatic validation.

For example, a user creation endpoint requiring full name (2-10 characters), email (6-20 characters), and passcode (6-20 characters):

  • Add validation annotations to the DTO:
@Data
public class UserRequest {
    private Long id;

    @NotNull
    @Length(min = 2, max = 10)
    private String fullName;

    @NotNull
    @Length(min = 6, max = 20)
    private String email;

    @NotNull
    @Length(min = 6, max = 20)
    private String passcode;
}
  • Enable validation in the controller:
@PostMapping("/create")
public Response createUser(@RequestBody @Validated UserRequest userRequest) {
    return Response.success();
}

Both @Valid and @Validated work for this scenario. Validation failures throw a MethodArgumentNotValidException, which Spring converts to a 400 Bad Request response by default.

Validating requestParam/PathVariable Parameters

For GET requests with individual parameters, apply validation annotations directly to method parameters and add @Validated to the controller class. Validation failures throw a ConstraintViolationException.

Example:

@RequestMapping("/api/users")
@RestController
@Validated
public class UserApiController {

    @GetMapping("/{userId}")
    public Response getById(@PathVariable("userId") @Min(10000000000000000L) Long userId) {
        UserRequest user = new UserRequest();
        user.setId(userId);
        user.setEmail("user@example.com");
        user.setFullName("Jane Doe");
        user.setPasscode("secure123456");
        return Response.success(user);
    }

    @GetMapping("/find")
    public Response findByEmail(@Length(min = 6, max = 20) @NotNull String email) {
        UserRequest user = new UserRequest();
        user.setId(10000000000000003L);
        user.setEmail(email);
        user.setFullName("John Smith");
        user.setPasscode("password123");
        return Response.success(user);
    }
}

Global Exception Handling

To return user-friendly validation error responses, implement a global exception handler:

@RestControllerAdvice
public class GlobalValidationExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Response handleRequestBodyValidationErrors(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder("Validation failed: ");
        for (FieldError error : result.getFieldErrors()) {
            errorMsg.append(error.getField()).append(": ").append(error.getDefaultMessage()).append(", ");
        }
        return Response.error(ErrorCodes.VALIDATION_FAILED, errorMsg.toString().trim());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Response handleMethodParameterValidationErrors(ConstraintViolationException ex) {
        return Response.error(ErrorCodes.VALIDATION_FAILED, ex.getMessage());
    }
}

Advanced Usage

Group Validation

When different endpoints use the same DTO but require different validation rules, use group validation. For example, user creation doesn't require an ID, but modification does.

  • Define validation groups and annotate fields:
@Data
public class UserRequest {
    @Min(value = 10000000000000000L, groups = Modify.class)
    private Long id;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 2, max = 10, groups = {Create.class, Modify.class})
    private String fullName;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 6, max = 20, groups = {Create.class, Modify.class})
    private String email;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 6, max = 20, groups = {Create.class, Modify.class})
    private String passcode;

    public interface Create {}
    public interface Modify {}
}
  • Specify the validation group in the controller:
@PostMapping("/create")
public Response createUser(@RequestBody @Validated(UserRequest.Create.class) UserRequest userRequest) {
    return Response.success();
}

@PostMapping("/modify")
public Response modifyUser(@RequestBody @Validated(UserRequest.Modify.class) UserRequest userRequest) {
    return Response.success();
}

Nested Validation

If a DTO contains another object, use nested validation by adding @Valid to the nested field. For example, including a user profile in the request:

@Data
public class UserRequest {
    @Min(value = 10000000000000000L, groups = Modify.class)
    private Long id;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 2, max = 10, groups = {Create.class, Modify.class})
    private String fullName;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 6, max = 20, groups = {Create.class, Modify.class})
    private String email;

    @NotNull(groups = {Create.class, Modify.class})
    @Length(min = 6, max = 20, groups = {Create.class, Modify.class})
    private String passcode;

    @NotNull(groups = {Create.class, Modify.class})
    @Valid
    private Profile profile;

    @Data
    public static class Profile {
        @Min(value = 1, groups = Modify.class)
        private Long profileId;

        @NotNull(groups = {Create.class, Modify.class})
        @Length(min = 2, max = 10, groups = {Create.class, Modify.class})
        private String profileName;

        @NotNull(groups = {Create.class, Modify.class})
        @Length(min = 2, max = 10, groups = {Create.class, Modify.class})
        private String role;
    }

    public interface Create {}
    public interface Modify {}
}

Nested validation works with groups and also applies to collections (e.g., List<Profile> will validate each element in the list).

Collection Validation

To validate a JSON array directly in the request body, wrap the collection in a custom class with @Valid and @Delegate (requires Lombok 1.18.6+):

public class ValidatedList<E> implements List<E> {
    @Delegate
    @Valid
    private List<E> items = new ArrayList<>();

    @Override
    public String toString() {
        return items.toString();
    }
}

Use it in the controller:

@PostMapping("/bulk-create")
public Response bulkCreate(@RequestBody @Validated(UserRequest.Create.class) ValidatedList<UserRequest> userList) {
    return Response.success();
}

Custom Validation

For business-specific rules, create custom validation annotations. For example, validate an encrypted ID (32-256 hex characters):

  • Define the custom annotation:
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = ValidEncryptedIdValidator.class)
public @interface ValidEncryptedId {
    String message() default "Invalid encrypted ID format";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
  • Implement the validator:
public class ValidEncryptedIdValidator implements ConstraintValidator<ValidEncryptedId, String> {
    private static final Pattern HEX_PATTERN = Pattern.compile("^[a-f0-9]{32,256}$", Pattern.CASE_INSENSITIVE);

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return HEX_PATTERN.matcher(value).matches();
    }
}

Programmatic Validation

To trigger validation manually (outside of automatic controller validation), inject the Validator bean and call its API:

@Autowired
private Validator validator;

@PostMapping("/validate-and-create")
public Response validateAndCreate(@RequestBody UserRequest userRequest) {
    Set<ConstraintViolation<UserRequest>> violations = validator.validate(userRequest, UserRequest.Create.class);
    
    if (!violations.isEmpty()) {
        for (ConstraintViolation<UserRequest> violation : violations) {
            System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
        }
    }
    
    return Response.success();
}

Fail-Fast Mode

By default, Spring Validation validates all fields before throwing an exception. Enable fail-fast mode to stop validation at the first error:

@Bean
public Validator validator() {
    ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory();
    return factory.getValidator();
}

@Valid vs @Validated Comparison

Feature @Valid @Validated
Provider JSR-380 Specification Spring Framework
Group Support No Yes
Allowed Locations METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE TYPE, METHOD, PARAMETER
Nested Validation Yes No

Implementation Principles

requestBody Validation Flow

In Spring MVC, RequestResponseBodyMethodProcessor handles @RequestBody parameters. The validation logic is in the resolveArgument method:

public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor {
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        parameter = parameter.nestedIfOptional();
        Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
        String name = Conventions.getVariableNameForParameter(parameter);

        if (binderFactory != null) {
            WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
            if (arg != null) {
                validateIfApplicable(binder, parameter);
                if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
                    throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
                }
            }
            if (mavContainer != null) {
                mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
            }
        }
        return adaptArgumentIfNecessary(arg, parameter);
    }
}

The validateIfApplicable method checks for @Valid or @Validated annotations and triggers validation using the underlying Hibernate Validator.

Method-Level Validation Flow

Method-level validation (for individual parameters) uses AOP. MethodValidationPostProcessor registers an advisor that applies MethodValidationInterceptor to beans annotated with @Validated:

public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true);
        this.advisor = new DefaultPointcutAdvisor(pointcut, createMethodValidationAdvice(this.validator));
    }

    protected Advice createMethodValidationAdvice(Validator validator) {
        return new MethodValidationInterceptor(validator);
    }
}

The interceptor validates method parameters before invocation and return values after invocation:

public class MethodValidationInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (isFactoryBeanMetadataMethod(invocation.getMethod())) {
            return invocation.proceed();
        }

        Class<?>[] groups = determineValidationGroups(invocation);
        ExecutableValidator execValidator = this.validator.forExecutables();
        Method targetMethod = invocation.getMethod();

        // Validate parameters
        Set<ConstraintViolation<Object>> paramViolations = execValidator.validateParameters(
                invocation.getThis(), targetMethod, invocation.getArguments(), groups);
        if (!paramViolations.isEmpty()) {
            throw new ConstraintViolationException(paramViolations);
        }

        Object result = invocation.proceed();

        // Validate return value
        Set<ConstraintViolation<Object>> returnViolations = execValidator.validateReturnValue(
                invocation.getThis(), targetMethod, result, groups);
        if (!returnViolations.isEmpty()) {
            throw new ConstraintViolationException(returnViolations);
        }

        return result;
    }
}

Both validation flows ultimately delegate to Hibernate Validator for actual rule enforcement.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.