Best practices for Java parameter verification: In-depth analysis of Validator and @AssertTrue
1. Introduction
In enterprise-level application development, parameter verification is the first line of defense to ensure data quality. This article will introduce in-depth the use of Java Validator framework, especially how to combine it.@AssertTrue
Annotations implement complex business verification logic.
2. Environmental preparation
2.1 Dependency configuration
<dependency> <groupId></groupId> <artifactId>validation-api</artifactId> <version>2.0.</version> </dependency> <dependency> <groupId></groupId> <artifactId>hibernate-validator</artifactId> <version>6.1.</version> </dependency>
3. Introduction to basic annotations
Commonly used verification annotations include:
-
@NotBlank
: The string cannot be null and the length must be greater than 0 after removing spaces -
@Pattern
: Verify string format by regular expression -
@Size
: Verify the length range of strings, sets, arrays, etc. -
@AssertTrue
: The return value of the verification method must be true -
@NotNull
: Cannot be null -
@Min
: The value must be greater than or equal to the specified value -
@Max
: The value must be less than or equal to the specified value -
@Email
: Verify the mailbox format
4. Practical examples
4.1 Request object definition
@Data public class ImageRequest { /** * Image URL address */ @Pattern(regexp = "^(http|https)://.*", message = "Image URL format is incorrect") @Size(max = 1024, message = "The length of the image URL cannot exceed 1024 characters") private String imageUrl; /** * Base64 encoded picture data */ @Size(max = 10 * 1024 * 1024, message = "Base64 picture data cannot exceed 10MB") private String base64Image; /** * Equipment number */ @NotBlank(message = "The device number cannot be empty") private String deviceNo; /** * User ID */ @NotBlank(message = "User ID cannot be empty") private String userId; /** * Custom verification method: Make sure to provide at least one image data */ @AssertTrue(message = "One of the image URL or Base64 encoded image data must be provided") public boolean isImageDataValid() { return (imageUrl) || (base64Image); } }
4.2 Verification implementation
public class ValidationExample { private final Validator validator; public ValidationExample() { ValidatorFactory factory = (); = (); } public void validateRequest(ImageRequest request) { // Perform verification Set<ConstraintViolation<ImageRequest>> violations = (request); // If there is a verification error if (!()) { // Collect all verification error information String errorMessage = () .map(ConstraintViolation::getMessage) .collect(("; ")); ("Parameter verification failed:{}", errorMessage); throw new IllegalArgumentException("Parameter verification failed:" + errorMessage); } } }
5. @AssertTrue in-depth analysis
5.1 Basic usage
@AssertTrue
Annotations are used in complex business verification scenarios, especially when it involves correlation verification between multiple fields.
5.2 Naming Specifications
@AssertTrue(message = "Check message for failed verification") public boolean isXxxValid() { // Verification logic return true/false; }
5.3 Common usage scenarios
5.3.1 Mutex Field Verification
@AssertTrue(message = "Only one of the payment methods can be selected") public boolean isPaymentMethodValid() { return (alipay != null) ^ (wechatPay != null); }
5.3.2 Dependency field verification
@AssertTrue(message = "When selecting express delivery, the delivery address cannot be empty") public boolean isDeliveryAddressValid() { return !(deliveryType) || (deliveryAddress); }
5.3.3 Numerical range linkage verification
@AssertTrue(message = "The end time must be later than the start time") public boolean isTimeRangeValid() { return endTime != null && startTime != null && (startTime); }
6. Advanced Features
6.1 Group verification
public interface Create {} public interface Update {} @AssertTrue(message = "Create Rules", groups = {}) public boolean isCreateValid() { return ...; } @AssertTrue(message = "Check rules during update", groups = {}) public boolean isUpdateValid() { return ...; }
6.2 Combination verification rules
@AssertTrue(message = "Image data format verification failed") public boolean isImageFormatValid() { if ((imageUrl)) { return ("http") && ((".jpg") || (".png")); } if ((base64Image)) { return ("data:image/"); } return false; }
7. Best Practice Recommendations
Unified exception handling
- Create a global exception handler
- Return format for unifying verification failed
Performance optimization
- ValidatorFactory should be a singleton
- Avoid heavy-weight operations in the verification method
Code Specification
- The naming of verification methods must be standardized and descriptive
- Keep the verification logic simple and clear
And it has descriptive keeps the verification logic simple and clear
Test coverage
- Write a complete unit test
- Covering various boundary conditions
Document maintenance
- Record the business meaning of verification rules
- Update documents in a timely manner
This is the article about in-depth analysis of Java parameter verification Validator and @AssertTrue. For more related Java parameter verification Validator and @AssertTrue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!