如何在Spring Boot中使用@NotNull?

Gab*_*ado 3 validation bean-validation spring-boot

我有这种依赖性:

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

哪个版本由

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>
Run Code Online (Sandbox Code Playgroud)

我有这块:

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

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

    @NotNull
    private String urlCDI;

    //getters and setters
}
Run Code Online (Sandbox Code Playgroud)

SpringApplication.run班上有这样的香料:

@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan({ "otherPackages", "packageWhereCollectorPropertiesIs" })
Run Code Online (Sandbox Code Playgroud)

当我有application.properties这条线时

collector.urlCDI=https://www.cetip.com.br/Home
Run Code Online (Sandbox Code Playgroud)

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

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

   //inside some method
    URL url = new URL(props.getUrlCDI());
Run Code Online (Sandbox Code Playgroud)

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

Séb*_*ert 5

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