Using Hibernate Validator and Commons‑Lang3 for Parameter Validation in Spring Boot Controllers
This article explains how to place parameter validation in the appropriate layer, introduces Hibernate Validator with Maven dependencies and common annotations, provides a validated entity example, shows controller usage with @Valid/@Validated, and demonstrates useful Commons‑Lang3 utilities for string and collection checks.
The author, a senior architect, explains why parameter validation should be placed in the controller layer for non‑business rules and in the service layer for business‑related checks.
He introduces Hibernate Validator as a convenient validation framework, showing the Maven dependency and common annotations such as @NotBlank , @Pattern , and @Length .
An example entity is presented: public class DataSetSaveVO { @NotBlank(message = "user uuid is empty") @Pattern(regexp = "^[a-z0-9]+$", message = "user names can only be alphabetic and numeric") @Length(max = 48, message = "user uuid length over 48 byte") private String userUuid; @Pattern(regexp = "^[A-Za-z0-9]+$", message = "data set names can only be letters and Numbers") @Length(max = 48, message = "file name too long") @NotBlank(message = "file name is empty") private String name; @Length(max = 256, message = "data set description length over 256 byte") @NotBlank(message = "data set description is null") private String description; } demonstrating field‑level constraints and custom messages.
In a Spring Boot controller the method is written as: @PostMapping public ResponseVO createDataSet(@Valid @RequestBody DataSetSaveVO dataSetVO) { return ResponseUtil.success(dataSetService.saveDataSet(dataSetVO)); } where @Valid (or @Validated) triggers the defined validations.
The article also introduces Apache Commons‑Lang3, providing its Maven dependency and illustrating typical utility methods such as StringUtils.isEmpty , StringUtils.isBlank , and CollectionUtils.isEmpty with sample test code.
Finally, it notes that when built‑in constraints are insufficient, developers can create custom validation annotations to meet specific requirements.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.