小编典典

Spring中的自定义约束验证器不起作用

spring-boot

正在使用Spring-Boot框架。我实际上是在定义“自定义约束验证器”。但这对我不起作用。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.abcinc.lab</groupId>
    <artifactId>spring-boot-lab</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-lab</name>
    <description>Spring Boot Lab</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RC1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

ValidString.java

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

/**
 * @author bineeth
 *
 */
@Documented
@Retention(RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Constraint(validatedBy = ValidStringValidator.class)
public @interface ValidString {
  String message() default "Invalid string!";

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

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

ValidStringValidator.java

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

/**
 * @author bineeth
 * @param <A>
 * @param <T>
 *
 */
public class ValidStringValidator implements ConstraintValidator<ValidString, String> {

  @Override
  public void initialize(ValidString constraintAnnotation) {
    ConstraintValidator.super.initialize(constraintAnnotation);
  }

  @Override
  public boolean isValid(String data, ConstraintValidatorContext context) {
    return (null != data && (!data.trim().equals("")));
  }
}

这是我使用约束的地方。

SpringBootComponentImpl.java

import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.abcinc.lab.springbootlab.validation.ValidString;

/**
 * @author bineeth
 *
 */
@Component
public class SpringBootComponentImpl implements SpringBootComponent {

  @SuppressWarnings("serial")
  @Override 
  public Map<String, String> execute(final @ValidString String commandType) {
    return new HashMap<String, String>() {
      {
        put("execution", "success");
      }
    };
  }

}

也许可能错过了一些东西。但是还不能弄清楚。感谢任何帮助。谢谢!


阅读 545

收藏
2020-05-30

共1个答案

小编典典

您缺少两件事:

  1. 已经有一个标准的NotBlank注释来执行您的自定义验证
  2. 如果不使用注释Spring bean的方法参数,将不会对其进行验证@Validated
2020-05-30