Information About Implementing Spring Custom Annotations

Asked 2 years ago, Updated 2 years ago, 120 views

Spring Custom Annotation Story - Qiita

I saw the above website.
I understand that Constraint Annotation has a fixed model (message(), groups(), and payload(), but is it possible to add a condition for setting full-width alphanumeric characters to error to the class below?

Annotation to limit the maximum length by separating half and full-width characters It says so, but I don't know which code is used to limit it.
Please let me know.

@Target({FIELD})
@Retention (RUNTIME)
@ Documented
@Constraint(validatedBy={CustomSizeValidator.class})
public@interfaceCustomSize{

    String message() default "{validation.CustomSize.message}";
    Class <?> [ ] groups() default { };
    Class <?extends Payload > [ ] payload() default { };
    int max();

    @Target ({FIELD})
    @Retention (RUNTIME)
    @ Documented
    @ interface List {
        CustomSize [] value();
    }
}

java spring

2022-09-29 22:23

1 Answers

The referenced linked code implements validation in the CustomSizeValidator class isValid method

@Override
  public boolean isValid(String value, ConstraintValidatorContext){
    // CustomSizeUtil is a class that describes only check logic
    // getLength return value is int
    return CustomSizeUtil.getLength(value)<=max;
  }

Yes.
In this method, the string passed by the argument is

Full-width lowercase letters

You can achieve this by implementing to return false if contains .

In addition, the linked code is

Count half-width and full-width separately

This is what we call the CustomSizeUtil.getLength(value) method.
(I can't really imagine the behavior from Japanese.)

@Override 
public void initialize (CustomSize customSize) {
 max = customSize.max(); 
}

Then, I haven't read the isValid method, but why does the above code correspond to initializing the isValid method?

This validation is based on implementing the Bean Validation specification, and the answer to the above question is "This specification.

In fact, the initialize and isValid methods are invoked by the framework.


2022-09-29 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.