首页 > 解决方案 > 如何在 Spring Boot 中使用 @NotNull?

问题描述

我有这个依赖:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

它的版本由哪个管理

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

我有这件作品:

import javax.validation.constraints.NotNull;
//other imports ommited

@Component
@ConfigurationProperties(prefix = "collector")
public class CollectorProperties {

    @NotNull
    private String urlCDI;

    //getters and setters
}

我的SpringApplication.run班级有这样的照片:

@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan({ "otherPackages", "packageWhereCollectorPropertiesIs" })

当我有我application.properties的这条线

collector.urlCDI=https://www.cetip.com.br/Home

它的工作原理与其他 spring bean 中的预期相同:

//@Component class variables:
@Autowired
private CollectorProperties props;

   //inside some method
    URL url = new URL(props.getUrlCDI());

但是当我删除它或更改属性键时,我会得到很多 NPE 而不是验证错误。我做错了什么?不hibernate-validator包含javax.validation.constraints.NotNull接口的实现?

标签: validationspring-bootbean-validation

解决方案


将“@Validated”注释添加到您的属性类


推荐阅读