Spring验证@NotNull不验证

时间:2018-07-31 02:57:12

标签: java spring spring-boot spring-restcontroller spring-validator

我正在尝试使用Spring Validator验证POST请求。这是我要验证的对象:

@Validated
public class Request implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id1;
    private Long id2;   
    private String s;   
    private List<Mapping> mappings;

    public Request() {}
    public Request (Long id1, Long id2, String s, List<Mapping> mappings) {
        this.id1 = id1;
        this.id2 = id2;
        this.s = s;
        this.mappings = mappings;
    }

    //getter() and setter() methods.
}

这是Mapping类:

@Validated
public class Mapping implements Serializable {
    private static final long serialVersionUID = 1L;
    @JsonProperty(value="id")
    private Long id;

    @JsonProperty(value="string")
    private String string;

    @JsonProperty(value="account_id")
    @NotNull
    private String accountId;

    @JsonProperty(value="last_updated_at")
    @NotNull    
    private OffsetDateTime lastUpdatedAt;

    // Getter and setters()
    // I'll skip the getter() and setter() for id and string fields.
    @Override
    public String getAccountId() {
        return accountId;
    }

    @Override
    public void setAccountId (@NotNull String accountId) {
        this.accountId = accountId;
    }

    @Override
    public OffsetDateTime getLastUpdatedAt() {
        return lastUpdatedAt;
    }

    @Override
    public void setLastUpdatedAt(@NotNull OffsetDateTime lastUpdatedAt) {
        this.lastUpdatedAt = lastUpdatedAt;
    }
}

这是要发布的消息:

[Request [id1=null, id2=null, s=6eq2J6, mappings=

[Mapping [id=2779, string=6eq2J6, accountId=null, lastUpdatedAt=null]]]]

这是我收到请求的方式,但是bindingResult.hasErrors()始终为空。 pushRequest与发送的完全相同。

@RestController
@RequestMapping(value="/${path}", method={RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
@Validated
public class MappingController {

@PostMapping(value="/", consumes={"application/json"})
public void processMappings (@Valid @RequestBody Optional<Request> pushRequest, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        log.info("Error!");
    }
}
}

为什么当@NotNull的值为Null时,accountId和lastUpdatedAt不会使验证失败?

我试图通过搜索此错误来找到解决方案,解决方案是将@Validated添加到Request, Mapping and MappingController类中,但这不能解决问题。

另一种解决方案是将这些Beans添加到Main()类中,但这不能解决问题。

public class Main {
    public static void main(String[] args) {        
        SpringApplication.run(Main.class, args);        
        //System.out.println("version: " + SpringVersion.getVersion()); // version: 5.1.0.RC1
    }

    @Bean
    public javax.validation.Validator localValidatorFactoryBean() {
       return new LocalValidatorFactoryBean();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
                MethodValidationPostProcessor mvProcessor = new MethodValidationPostProcessor();
                mvProcessor.setValidator(validator());
                return mvProcessor;
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
                    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
                    validator.setProviderClass(HibernateValidator.class);
                    validator.afterPropertiesSet();
                    return validator;
    }
}

2 个答案:

答案 0 :(得分:1)

就我而言,我缺少验证依赖项。来自baeldung;

Starting with Boot 2.3, we also need to explicitly add the spring-boot-starter-validation dependency:

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

答案 1 :(得分:0)

我想我找到了答案,这要归功于这篇文章:

jsr-303-valid-annotation-nested-object-not-working

因此,一旦我在这些字段中添加了@Valid:

@Valid
private List<Mapping> mappings;

“映射”中的这些字段:

@JsonProperty(value="account_id")
    @Valid
    @NotNull
    private String accountId;

    @JsonProperty(value="last_updated_at")
    @Valid
    @NotNull    
    private OffsetDateTime lastUpdatedAt;

验证开始工作。

我还从@NotNull方法中删除了setter()

Setters()这样:

@Override
    public void setAccountId (String accountId) {
        this.accountId = accountId;
    }    

    @Override
    public void setLastUpdatedAt(OffsetDateTime lastUpdatedAt) {
        this.lastUpdatedAt = lastUpdatedAt;
    }

我的代码也可以在没有添加到Main()的任何Validator bean的情况下工作。