如何在 spring 启动时使用@NotNull?
How to use @NotNull with spring boot?
我有这种依赖性:
<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
class 有这张照片:
@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan({ "otherPackages", "packageWhereCollectorPropertiesIs" })
当我 application.properties
有这条线时
collector.urlCDI=https://www.cetip.com.br/Home
它像在其他 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
接口的实现吗?
为您的属性添加“@Validated”注释class
我有这种依赖性:
<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
class 有这张照片:
@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan({ "otherPackages", "packageWhereCollectorPropertiesIs" })
当我 application.properties
有这条线时
collector.urlCDI=https://www.cetip.com.br/Home
它像在其他 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
接口的实现吗?
为您的属性添加“@Validated”注释class