如何在Spring Boot中使用@NotNull?

时间:2018-08-14 00:56:57

标签: validation spring-boot bean-validation

我有这种依赖性:

<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

它可以像在其他春豆中一样起作用:

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

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

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

1 个答案:

答案 0 :(得分:4)

在您的媒体资源类中添加“ @Validated”注释