Custom parameter validation annotations

Custom parameter annotations


Today, when solving the test loophole, it is necessary to add parameter verification to the parameters of each class. Among them, I want to add special character interception through regular expressions. Because there are many classes required, it will be troublesome to add one by one, so I thought of defining it myself. An annotation will be more convenient, just do it, the general process of the following custom annotation.

Custom rule annotation process

Rule matching class definition

First, you need to define a rule class. This class inherits the ConstraintValidator class. This class requires two parameters, which are the annotation class defined later. The annotation class defined here is SpecialMatch, and the type of the validation parameter. Here, the String type is used as an example.

package com.xasj.common.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

 * @author needless to say
 * @Date 2022/10/11 16:18
 * @Description
public class SpecialCharacterMatch implements ConstraintValidator<SpecialMatch, String> {
    private static final Pattern PATTERN = Pattern.compile("[^`!~@#$¥%^&*()+=\\[\\]\\\\|'\"""'';;:<>,<>,?/?{}]*$");
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value != null) {
            Matcher matcher = PATTERN.matcher(value);
            return matcher.matches();
        return true;

Annotation class definition

Then you need to define an annotation class, which is used when defining the rule class above, and this annotation class is the annotation directly used on the request parameter class.

package com.xasj.common.annotation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

 * @author needless to say
 * @Date 2022/10/11 16:22
 * @Description Check special character comments
@Constraint(validatedBy = {SpecialCharacterMatch.class})
public @interface SpecialMatch {
    String message() default "cannot contain except'-''_'special characters other than"; // Matching failure prompt message content
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

The annotation class contains several other annotations:
@Target: The use target of the annotation, here the selection acts on the field (FIELD) and the parameter (PARAMTERE), it has 8 types, which are defined in the ElementType enumeration type
The scope of @Target has the following types:
1.@Target(ElementType.TYPE) - interface, class, enumeration, annotation
2.@Target(ElementType.FIELD) - constants of fields and enumerations
3.@Target(ElementType.METHOD) - method
4.@Target(ElementType.PARAMETER) - method parameters
5.@Target(ElementType.CONSTRUCTOR) - Constructor
6.@Target(ElementType.LOCAL_VARIABLE) - local variable
7.@Target(ElementType.ANNOTATION_TYPE) - annotation
8.@Target(ElementType.PACKAGE) - package, used to record the package information of the java file
@Retention: The function of this annotation is to define how long the annotation it annotates will be retained. Here, RunTime is selected, and its three types are defined in the RetentionPolicy enumeration class
Types of @Retention include:
1.@Retention(SOURCE): The annotation is only retained in the source file. When the Java file is compiled into a class file, the annotation is abandoned; it is ignored by the compiler
2.@Retention(CLASS): The annotation is retained in the class file, but it is abandoned when the jvm loads the class file, which is the default life cycle
3.@Retention(RUNTIME): The annotation is not only saved in the class file, but still exists after the jvm loads the class file
@Documented: This annotation is related to document generation. If an annotation @B is annotated with @Documented, the class modified by @B will display @B when generating a document. If @B is not @Documented standard, @B will not appear in the final generated document. (haven't tried it specifically)
@Constraint: This annotation is used to identify the rule validation class used, validatedBy fill in the rule class defined above

Use custom annotations

Using custom annotations is the same as other annotations, @ plus the class name of the annotated class


The content of the check is that the string does not contain all special characters except - and _


The custom annotations made this time can be completed using the @Pattern regular matching annotation, but using the @Pattern annotation requires a long regular expression each time, so use custom annotations to achieve this matching effect, define custom annotations It can be reused, and defining different annotations according to specific business needs can effectively improve efficiency.

Tags: Java Spring

Posted by PHPTOM on Wed, 12 Oct 2022 12:27:57 +1030