Home > Enterprise >  Default values in custom annotation not working
Default values in custom annotation not working

Time:11-16

I'm new in JAVA. I created a new custom annotation for custom validation in SPRING, but when I run the app I see this error:

  The annotation @CourseCode must define the attribute groups
  The annotation @CourseCode must define the attribute message
  The annotation @CourseCode must define the attribute payload
  The annotation @CourseCode must define the attribute value

Here is my implementation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.validation.Constraint;
import javax.validation.Payload;

@Constraint(validatedBy = CourseCodeConstraintValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CourseCode {
    public String value() default "course-";

    public String message() default "must start with course-";

    public Class<?>[] groups() default {};

    public Class<? extends Payload>[] payload() default {};

}

Here is my usage

    @CourseCode
    private String courseCode;

Here is my CourseCodeConstraintValidator.

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CourseCodeConstraintValidator implements ConstraintValidator<CourseCode, String>{

    private String coursePrefix;

    @Override
    public void initialize(CourseCode courseCode) {
        coursePrefix = courseCode.value();
    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext constraintValidatorContext) {

        boolean result = code.startsWith(coursePrefix);

        return result;
    }
}

I expected the default values I defined in the class would be used.

CodePudding user response:

After lots of hours of research, I gave up for a couple of days. Now I came back to it and suddenly discovered that switching perspective in eclipse after restarting the PC has done the trick and now it works as I expected. Thanks to everybody who tried to help.

  • Related