Jordan is the basketball god I have heard of, Kobe is the basketball god I have seen. This article has been
https://www.yourbatman.cnIncluded, which together with the Spring technology stack, MyBatis, JVM, middleware and other small and beautiful
columnFor free learning. Follow the public account [
The Utopia of BAT【 break down one by one, thoroughly grasp, refuse to be tasted.

The foreword ✍

Hello, I’m YourBatman.

The last two articles should get you excited about Bean Validation. From a consumer perspective, what interfaces and interface methods should we know and be familiar with in order to complete Validation using Bean Validation?

Version of the agreement

  • Bean Validation version:2.0.2
  • Hibernate Validator Version:6.1.5. The Final

✍ body

Bean Validation is a Java EE standard technology with JSR abstractions, so you can use Bean Validation in a standards-oriented manner. It doesn’t matter whether it is implemented by Hibernate or Apache.

Tips: To facilitate the following examples, some simple, common methods are extracted as follows:

public abstract class ValidatorUtil { public static ValidatorFactory obtainValidatorFactory() { return Validation.buildDefaultValidatorFactory(); } public static Validator obtainValidator() { return obtainValidatorFactory().getValidator(); } public static ExecutableValidator obtainExecutableValidator() { return obtainValidator().forExecutables(); } public static <T> void printViolations(Set<ConstraintViolation<T>> violations) { -> v.getPropertyPath() + " " + v.getMessage() + ": " + v.getInvalidValue()).forEach(System.out::println); }}


Validator interface: The entry point for validation that validates a Java Bean, a property, a method, a constructor, and so on.

public interface Validator {

It’s the one API that users touch the most, and it’s certainly the most important. Each of these methods is explained below + examples of usage.

Validate: Validate the Java Bean

<T> Set<ConstraintViolation<T>> validate(T object, Class<? >... groups);

Verify all constraints on the Java Bean object. Here is an example:

Java Bean:

@ScriptAssert(script = "", lang = "javascript")
public class User {

    private String name;
    @Length(min = 20)
    private String fullName;

public void test5() {
    User user = new User();

    Set<ConstraintViolation<User>> result = ValidatorUtil.obtainValidator().validate(user);

@ScriptAssertIs Hibernate Validator provides a script constraint annotations, can realize logic collapse field calibration, function is very powerful, the explanation

Run the program, console output:

Execution of the script expression "" does not return the desired result: User(name=YourBatman, fullName=null) fullName cannot be null: null

As expected. Note: NULL is legal for @length constraints in fullName, so there will be no log output

Verify all constraints on the Java Bean, including: 1. Constraints on attributes; 2. Constraints on classes

ValidateProperty: ValidateProperty validates the specified property

<T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<? >... groups);

Validate all constraints on a property in a Java Bean. Here is an example:

public void test6() {
    User user = new User();

    Set<ConstraintViolation<User>> result = ValidatorUtil.obtainValidator().validateProperty(user, "fullName");

Run the program, console output:

The fullName length needs to be between 20 and 2147483647: YourBatman

As expected. It validates all constraints on the property, only on the property, not elsewhere.

ValidateValue: ValidateValue

Verifies that a value conforms to all constraints on the specified attribute. If I assign this value to this property, is it legal?

<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<? >... groups);

This validation method is special: it checks whether a value satisfies all the constraints of a property without first having an object instance, so it can be used to check whether a value satisfies all the constraints of a property. Here is an example:

@Test public void test7() { Set<ConstraintViolation<User>> result = ValidatorUtil. ObtainValidator (.) validateValue (User. The class, "fullName," "A brother"); ValidatorUtil.printViolations(result); }

Run the program and output:

The fullName length should be between 20 and 2147483647: brother A

ValidateValue (user. class, “fullName”, “yourbatman-yourbatman “); If you run the program again, the console will no longer print the string length greater than 20.

Gets the Class type description information

BeanDescriptor getConstraintsForClass(Class<? > clazz);

This clazz can be a class or interface type. Beandescriptor: Describes a constrained Java Bean and its associated constraints. Here is an example:

@Test public void test8() { BeanDescriptor beanDescriptor = obtainValidator().getConstraintsForClass(User.class); System. The out. Println (" is whether you need this kind of check: "+ beanDescriptor. IsBeanConstrained ()); / / retrieve attributes, methods, constructors of constraint Set < PropertyDescriptor > constrainedProperties = beanDescriptor. GetConstrainedProperties (); Set<MethodDescriptor> constrainedMethods = beanDescriptor.getConstrainedMethods(MethodType.GETTER); Set<ConstructorDescriptor> constrainedConstructors = beanDescriptor.getConstrainedConstructors(); System.out.println(" Properties to be validated: "+ constrainedProperties); System.out.println(" methods to verify: "+ constrainedMethods); System.out.println(" Constructors to be verified: "+ ConstrainedConstructors); PropertyDescriptor fullNameDesc = beanDescriptor.getConstraintsForProperty("fullName"); System.out.println(fullNameDesc); System. The out. Println (" fullName attribute constraints annotate number: "fullNameDesc. GetConstraintDescriptors (). The size ()); }

Run the program and output:

Whether this class needs validation: true The property that needs validation: [PropertyDescriptorImpl{propertyName=name, cascaded=false}, PropertyDescriptorImpl{propertyName=fullName, [] PropertyDescriptorImpl{PropertyName = FullName, Cascaded = False} FullName = FullName 2

Gets the Executable validator

@ since 1.1 ExecutableValidator forExecutables ();

The Validator API, which has been around since 1.0, only validates Java beans, not methods, constructor parameters, return values, etc.

Version 1.1 provides the ExecutableValidator API to address this need, and instances of it can be obtained by calling the Validator method, which is handy. Refer to the previous article for details on how to use ExecutableLabs.


Constraint violation details. This object holds the context of the constraint violation as well as the description message.

// <T bb0: root bean public interface ConstraintCheesecake <T> {}

In simple terms, it stores the result of executing all constraints (whether Java Bean constraints, method constraints, etc.), and provides an API to access the result.

Tip: This object will only be generated if the constraint is violated. One constraint violation corresponds to one instance

// interpolated message String getMessage(); String getMessageTemplate(); String getMessageTemplate(); String getMessageTemplate(); // The path to the property starting with the rootBean. For example: Parent.fullName Path getPropertyPath(); // Tell which constraint didn't pass ConstraintDescriptor<? > getConstraintDescriptor();

Example: Omitted.


Validator context from which to create a Validator instance. Different contexts can create different instances (by different, I mean different internal components) to meet various personalized customization requirements.

The ValidatorContext interface provides Settings to customize the core components of the Validator. These are the five core components of the Validator Validator:

public interface ValidatorContext { ValidatorContext messageInterpolator(MessageInterpolator messageInterpolator); ValidatorContext traversableResolver(TraversableResolver traversableResolver); ValidatorContext constraintValidatorFactory(ConstraintValidatorFactory factory); ValidatorContext parameterNameProvider(ParameterNameProvider parameterNameProvider); ValidatorContext clockProvider(ClockProvider clockProvider); // @Since 2.0 value extractor. ValidatorContext addValueExtractor(ValueExtractor<??); // ValueExtractor<?? > extractor); Validator getValidator(); }

You can set different component implementations using these methods, and when you set them up, you can use getValidator() to get a custom validator, not a generic one. So, the first thing you need to do is get a ValidatorContext instance, and there are two ways to do that.

Method 1: New yourself

@Test public void test2() { ValidatorFactoryImpl validatorFactory = (ValidatorFactoryImpl) ValidatorUtil.obtainValidatorFactory(); // Use the default Context. ValidatorContext = new validatorContextPL (validatorFactory) validatorContext = new validatorContextPL (validatorFactory) .parameterNameProvider(new DefaultParameterNameProvider()) .clockProvider(DefaultClockProvider.INSTANCE); / / by the context, the validator instances (note: calls for many times, the instance is multiple yo) System. Out. The println (validatorContext. GetValidator ()); }

Run the program, console output:


This is the most direct way. New whatever you want. However, there are drawbacks to using it in this way, mainly in these two aspects:

  1. Not abstract enough. Well, the new way has nothing to do with abstraction
  2. Strongly coupled Hibernate Validator API, such as:org.hibernate.validator.internal.engine.ValidatorContextImpl#ValidatorContextImpl

Way two: factory generation

ValidatorContext is created by passing the validatorContext factory to the validatorContext factory instead of the factory. As it happens, ValidatorFactory also provides a corresponding method:

ValidatorContext usingContext();

This method is used to get an instance of ValidatorContext, which is highly abstract, independent of the underlying API, is the recommended way to get it, and has the effect of streaming programming when used, as shown below:

public void test3() {
    Validator validator = ValidatorUtil.obtainValidatorFactory().usingContext()
            .parameterNameProvider(new DefaultParameterNameProvider())

Obviously, this approach is recommended.

Get the two poses of the Validator instance

At the end of the article, look back at the two poses taken by the Validator instance. The Validator interface is the primary API for performing data validation (Java Bean validation, method validation, etc.). With that said, here’s a summary of how to get it.

Way one: direct factory acquisition

public void test3() {
    Validator validator = ValidatorUtil.obtainValidatorFactory().getValidator();

This way is very simple, simple, very friendly to beginners, simple entry, obvious advantages. All components use default mode to save worry. If you want to pick a disadvantage, it certainly is some: unable to meet the needs of personalization, customization, in plain English: unable to customize the implementation of the five components + value extractor.

As such a good Java EE standard technology, how can it be less open to extension? Go on to way two

Method two: from the context

The Validator context is a valid context, and the Validator context is a valid context, and the Validator context is a valid context.

Sample code:

public void test3() {
    Validator validator = ValidatorUtil.obtainValidatorFactory().usingContext()
            .parameterNameProvider(new DefaultParameterNameProvider())

This approach gives you a great deal of customization, and you can specify core component implementations to suit your needs.

These two ways combined, is not the typical default + custom extension collocation? In addition, the Validator is thread-safe. In general, an application only needs to initialize one instance of the Validator, so it is recommended to use the second method for initialization, which is more user-friendly.

✍ summary

In this article, we look at how to use Bean Validation from a user’s perspective, and what standard interface APIs you need to know. With this knowledge, you should be able to handle most cases easily.

The specification interface/standard interface generally solves most problems. This is the boundary of the specification. Some can and some can’t

Of course, these are the basics. To understand the functionality of Bean Validation, it is important to have a deeper understanding of the Hibernate Validator implementation because it provides a good complement to some of the more commonly used cases, as we will see below.

Recommend reading:
  • 1. This first post will improve your understanding of Bean Validation data Validation
  • Validation: Bean Validation: Validation: Bean Validation

♥ ♥ Brother A

Author A brother (YourBatman)
Personal site
E-mail [email protected]
WeChat fsx641385712
Active platform
The public, Bat Utopia (ID: Bat-Utopia)
Knowledge of the planet The Utopia of BAT
Daily article recommendations Daily article recommendations