Understanding Bean Validation and Spring Validation in Java Applications
Bean Validation (JSR‑303/380) offers a standard, annotation‑driven API—implemented by Hibernate Validator—for declaring constraints such as @NotNull or @Email, while Spring integrates it via @Valid and @Validated (with group support and AOP‑based method validation), enabling automatic request‑body checks, custom constraints, and service‑layer validation, provided the proper annotations are applied.
Background: Data validation is essential in front‑end and back‑end development. Repeating validation logic across layers is error‑prone.
Bean Validation (JSR‑303/JSR‑380) provides a standard API for declarative constraints using annotations such as @NotNull, @NotEmpty, @Email, etc. Hibernate Validator is the reference implementation.
Spring supports two validation mechanisms: Spring Validation (@Validated) and JSR‑303 Bean Validation (@Valid). @Validated adds group support and works with Spring AOP to trigger automatic validation.
Typical usage includes:
Adding Maven dependencies for Hibernate Validator or spring-boot-starter-validation.
Applying constraint annotations on fields, getters, container elements, classes, and nested objects.
Programmatic validation via ValidatorFactory and ExecutableValidator for method‑level checks.
Example of field‑level constraints:
public class EntryApplicationInfoCmd {
@NotNull(message = "用户ID不为空")
private Long userId;
@NotEmpty(message = "证件类型不为空")
private String certType;
}Method‑level validation example:
public class MerchantMainApplyQueryService {
@NotNull
@Size(min = 1)
public List<@NotNull MainApplyStandDepositResp> getStanderNewDeposit(Long id) { ... }
}Group validation allows the same model to be validated differently in distinct scenarios, e.g., UpdateMerchantMainApplyCmd and AddMerchantMainApplyCmd groups.
Custom constraints can be created by defining an annotation with @Constraint and implementing ConstraintValidator.
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
String message();
Class
[] groups() default {};
Class
[] payload() default {};
}Spring automatically validates @RequestBody parameters in @RestController methods when @Validated or @Valid is present. The underlying mechanism involves RequestResponseBodyMethodProcessor, WebDataBinder, and SpringValidatorAdapter, which delegate to the JSR‑303 validator.
For service‑layer validation, MethodValidationPostProcessor creates AOP proxies that invoke ExecutableValidator.validateParameters before method execution.
Common pitfalls: forgetting to place @Validated on the service class, or expecting @Valid to trigger group validation.
In summary, Bean Validation provides a unified, annotation‑driven way to enforce data integrity, while Spring adds convenient integration and group support.
DeWu Technology
A platform for sharing and discussing tech knowledge, guiding you toward the cloud of technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.