自定义注释初始化方法不起作用

时间:2019-12-09 17:20:33

标签: java spring annotations customvalidator

这是我的注释类

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类,在这里我尝试验证输入字符串,无论它是否以给定的前缀开头并返回布尔值 true false 。 / p>

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

1 个答案:

答案 0 :(得分:0)

假设您有一个包含几个字段的模型,并且您正在尝试验证一个类型为String的code,并用@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文档:

  

标记属性,方法参数或方法返回类型以进行验证级联。   在验证属性,方法参数或方法返回类型时,将验证在对象及其属性上定义的约束。   此行为是递归应用的。

因此,基本上,您想将此@Valid注释应用于要验证其定义约束的对象。假设您在非常基本的控制器中使用Course模型。您可以这样注释POSTed Course对象:

@Controller
@RequestMapping
public class CourseController {

    @PostMapping
    public addNewCourse(@RequestBody @Valid Course newCourse) {
        // perform some persistence logic
    }
}

在进入@Valid方法之前,Course newCouse之前的newCourse注释将addNewCourse对象标记为待验证。

现在,您的代码应输入initialize()的{​​{1}}方法,然后从CourseCodeConstraintValidator执行验证逻辑