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

标签 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类,在这里我尝试验证输入字符串,无论它是否以给定的前缀开头,并返回 boolean 值truefalse

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/

相关文章:

php - Doctrine2/Symfony 2 @ParamConverter 使用自定义存储库方法删除未映射的参数

java - 数组列表在战斗逻辑中似乎无法正常工作?

java - @ExceptionHandler 不会捕获从 Spring Formatters 抛出的异常

spring - 如何在 Spring 4 中开启注解驱动验证?

java - Spring:将@RequestBody 注入(inject)@Bean

java - 如何设置maven在spring boot中构建在特定文件夹中?

hibernate - 使用注释与属性的多对多关系

java - 使用 selenium webdriver 单击元素不会产生预期结果

没有自签名证书的 javax.net.ssl.SSLPeerUnverifiedException : Hostname XXX not verified,

java - 统计字符串中某个字母出现的次数