没有String类型的@NotBlank验证器

Myr*_*lav 6 spring-boot

对于相当简单的配置类,我不断收到验证器错误

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;

@Component
@Data
@Validated
@ConfigurationProperties(prefix = "test")
public class TestProperties {
    @NotBlank
    String uri;
}
Run Code Online (Sandbox Code Playgroud)

错误是自我解释:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.NotBlank' validating type 'java.lang.String'. Check configuration for 'uri'
Run Code Online (Sandbox Code Playgroud)

但是根据Spring Boot文档,这应该可以工作。

Var*_*uil 5

根据 Spring-Boot 文档和 maven 中央仓库:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

包含验证器。如果您的依赖项中没有包含 spring-boot-starter-web,则只需添加验证器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)


Tha*_*hla 5

我有同样的问题并解决了。

正如Yogi在其回答中所述,有两种实现方式:

import javax.validation.constraints.NotBlank;
Run Code Online (Sandbox Code Playgroud)

import org.hibernate.validator.constraints.NotBlank;
Run Code Online (Sandbox Code Playgroud)

javax实施切换到hibernate一个解决了问题。

由于我没有使用Spring boot,因此必须添加到pom.xml中:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

  • 描述了import org.hibernate.validator.constraints.NotBlank; (6认同)

Yog*_*ogi -1

您可以使用以下与 Spring JPA 一起使用的选项:

  1. org.hibernate.validator.constraints。非空白
  2. javax.validation.constraints。不为空


归档时间:

查看次数:

7932 次

最近记录:

7 年 前