如何在Spring Boot中使用@NotNull? [英] How to use @NotNull with spring boot?
本文介绍了如何在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
与此行一起使用时
When I have my application.properties
with this line
collector.urlCDI=https://www.cetip.com.br/Home
它可以像在其他春豆中一样起作用:
It works as it was supposed inside other spring beans:
//@Component class variables:
@Autowired
private CollectorProperties props;
//inside some method
URL url = new URL(props.getUrlCDI());
但是当我删除它或更改属性键时,会得到很多NPE而不是验证错误.我做错了什么? hibernate-validator
是否不包含 javax.validation.constraints.NotNull
接口的实现?
But when I remove it or alter property key I get lots of NPE instead of validations errors. What I'm doing wrong? Doesn't hibernate-validator
contains an implementation of javax.validation.constraints.NotNull
interface?
推荐答案
在属性类中添加"@Validated"注释
Add ´@Validated' annotation to your properties class
这篇关于如何在Spring Boot中使用@NotNull?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文