Jakarta Bean Validation API's best practice in Java development
Jakarta Bean Validation API's best practice in Java development
Introduction:
Jakarta Bean Validation API (JSR 380) is a standard specification for verifying the Java object.It provides developers with a simple and flexible way to verify and limit data models.In Java development, using the Bean Validation API can effectively manage the integrity and effectiveness of input data and provide friendly error prompts.This article will introduce the best practice of Jakarta Bean Validation API in Java development, including using annotations, custom verification rules and international support.
1. Use annotation:
Bean Validation API uses annotations to mark the verification rules.Common annotations include@notnull,@siZe,@Pattern,@min,@max, etc.By adding these annotations to the attributes of the Java object, it can easily limit the value range, length, format, etc. of the attribute.For example, when verifying a username, you can use @Pattern annotations to limit it. It can only include letters and numbers.
public class User {
@Pattern (regexp = "^[a-za-z0-9] {4,16} $", message = "Username must be 4-16 letters or numbers")
private String username;
// ... other attributes and methods ...
}
2. Customized verification rules:
In addition to using predefined annotations, the Bean Validation API also provides the function of custom annotations and constraints.Through customized annotations and verifications, developers can implement specific verification rules according to business needs.For example, we can create a customized annotation @Unique to verify whether the username is unique.
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueValidator.class)
public @interface Unique {
String message () default "This value already exists";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The implementation of the verification device is as follows:
public class UniqueValidator implements ConstraintValidator<Unique, String> {
// Get resources such as EntityManager during initialization
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
// Customized verification logic, for example, to query whether the database judgment value is unique
}
}
By using custom annotations and verifications, we can achieve more flexible and complex verification rules.
3. International support:
Bean Validation API supports internationalization and can provide corresponding error information according to different language environments.Different languages can be defined by resource files to define different languages.For example, create ValidationMessages.properties files in Resource directory::
# English
javax.validation.constraints.Pattern.message=Invalid value
# Chinese
javax.Validation.Constraints.pattern.Message = invalid value
Then, in the annotation of attributes, the error message is specified through the `Message` attribute, and the Bean Validation API will select the corresponding error information according to the current language environment.
public class User {
@Pattern(regexp = "^[a-zA-Z0-9]{4,16}$", message = "{javax.validation.constraints.Pattern.message}")
private String username;
// ... other attributes and methods ...
}
Use ResourceBundle to control the current language environment:
Local.setdefault (local.english); // Set to English
Local.setdefault (local.chinese); // Set to Chinese
Summarize:
Jakarta Bean Validation API is a very useful tool in the development of Java, which can easily implement data model verification and restrictions.This article introduces the best practice of using the Bean Validation API in the Java development, including the use of annotations, custom verification rules and international support.By using the Bean Validation API reasonably, the readability and maintenance of the code can be improved, and the occurrence of errors and abnormalities can be reduced.