Dynamic xml file configuration hibernate validator constraint verification

Parent article  Entering parameters to verify the product schema

Generally, it is verified through annotations, and it is rare to see verification through configuration.

I found the official website document hibernate validator constraint from xml through Google

Hibernate Validator 8.0.0.Final - Jakarta Bean Validation Reference Implementation: Reference Guide

Q : Dynamic java constraints are written in the text, read the text, and validate the bean

A : As follows

<dependency>
                <groupId>org.hibernate.validator</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>8.0.0.Final</version>
            </dependency>

            <dependency>
                <groupId>jakarta.validation</groupId>
                <artifactId>jakarta.validation-api</artifactId>
                <version>3.0.2</version>
            </dependency>

In Java, you can use the Hibernate Validator's programmatic API to read constraint definitions and then use them to validate Java Beans. In this way, the constraint definitions can be written in a text file, and then these constraint definitions can be dynamically loaded at runtime.

Here is an example of constraint validation using the programmatic API:

public class Config {
    private String name;
    private int age;

    // getters and setters
}

public class ConfigValidator {
    public static void main(String[] args) throws IOException {
        // Load constraint definitions from text file
        InputStream inputStream = new FileInputStream("constraints.txt");
        String constraints = new String(inputStream.readAllBytes());

        // Parse constraint definitions using Hibernate Validator
        ValidatorFactory factory = Validation.byDefaultProvider().configure()
                .addMapping(new ByteArrayInputStream(constraints.getBytes()))
                .buildValidatorFactory();
        Validator validator = factory.getValidator();

        // Validate configuration using Hibernate Validator
        Config config = new Config();
        config.setName("John");
        config.setAge(17);
        Set<ConstraintViolation<Config>> violations = validator.validate(config);

        // Print validation errors
        if (!violations.isEmpty()) {
            for (ConstraintViolation<Config> violation : violations) {
                System.out.println(violation.getMessage());
            }
        }
    }
}

https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#_adding_mapping_streams

In this example, we first define a Config class, which contains some properties. We then created a ConfigValidator class that reads a text file called constraints.txt and parses it into constraint definitions using Hibernate Validator. Next, we validate the Config object with these constraint definitions and store the validation results in a collection of ConstraintViolation objects. If there are validation errors, you can iterate over the ConstraintViolation object and output an error message.

In the constraints.txt file, we can use Hibernate Validator's constraint definition language to define constraints. For example, here is an example of a constraints.txt file:

<?xml version="1.0" encoding="UTF-8"?>
<bean-validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-2.0.xsd">
    <constraint-mappings>
        <bean class="com.example.Config">
            <field name="name">
                <constraint annotation="javax.validation.constraints.NotNull"/>
            </field>
            <field name="age">
                <constraint annotation="javax.validation.constraints.Min">
                    <element name="value">18</element>
                </constraint>
            </field>
        </bean>
    </constraint-mappings>
</bean-validation-config>

In this example, we define a constraint map using XML format, which contains a constraint definition for a Config class. We use the field element to specify the attribute to be validated, and the constraint element to specify the constraint to apply. In this example, we have used two constraints @NotNull and @Min(18).

Guess you like

Origin blog.csdn.net/fei33423/article/details/130889388