这是我的注释类
package com.meet.springdemo.mvc.validation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Constraint(validatedBy = CourseCodeConstraintValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface CourseCode {
// define default course code
public String value() default "LUV";
// define default error message
public String message() default "must start with LUV";
// define default groups
public Class<?>[] groups() default {};
// define default payloads
public Class<? extends Payload>[] payload() default {};
}
这是我的constraintValidator类,在这里我尝试验证输入字符串,无论它是否以给定的前缀开头,并返回 boolean 值true或false。
package com.meet.springdemo.mvc.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CourseCodeConstraintValidator
implements ConstraintValidator<CourseCode, String> {
private String coursePrefix;
@Override
public void initialize(CourseCode theCourseCode) {
coursePrefix = theCourseCode.value();
}
@Override
public boolean isValid(String theCode,
ConstraintValidatorContext theConstraintValidatorContext) {
boolean result;
System.out.println("Course prefix : "+ coursePrefix);
System.out.println("Course code : "+ theCode);
if (theCode != null) {
result = theCode.startsWith(coursePrefix);
}
else {
result = true;
}
return result;
}
}
这里initialize()
初始化时未调用方法。并调用isValid()
不打印 System.out.println("Course prefix : "+ coursePrefix);
的任何内容.
比方说,输入字符串 theCode
对于 isValid()
是ABCDEF;
然后它显示输出为:
Course prefix :
Course code : ABCDEF
最佳答案
假设您有一个包含几个字段的模型,并且您正在尝试验证其中一个名为 code
的字段。类型为 String,注释为 @CourseCode
。假设该模型名为 Course
。所以类似:
public class Course {
@CourseCode
private String code;
// some other attributes here
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
// some other getters / setters here
}
Java提供了一个注解javax.validation.Valid
可用于约束验证。来自 javax.validation.Valid
的 Java 文档注释:
Marks a property, method parameter or method return type for validation cascading. Constraints defined on the object and its properties are be validated when the property, method parameter or method return type is validated. This behavior is applied recursively.
所以基本上你想应用这个 @Valid
您想要验证其定义的约束的对象上的注释。假设您正在使用 Course
一个非常基本的 Controller 中的模型。您可以注释已发布的 Course
像这样的对象:
@Controller
@RequestMapping
public class CourseController {
@PostMapping
public addNewCourse(@RequestBody @Valid Course newCourse) {
// perform some persistence logic
}
}
@Valid
Course newCouse
之前的注释标记newCourse
在我们输入 addNewCourse
之前,要验证对象方法。
现在您的代码应输入 initialize()
方法CourseCodeConstraintValidator
然后执行 isValid()
中的验证逻辑
关于java - 自定义注释初始化方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59253728/