【问题标题】:How to use @NotNull with spring boot?如何在 Spring Boot 中使用 @NotNull?
【发布时间】:2018-08-14 00:56:56
【问题描述】:

我有这个依赖:

<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 接口的实现吗?

【问题讨论】:

    标签: validation spring-boot bean-validation


    【解决方案1】:

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

    【讨论】:

    • 确实,如果我仔细观察here 我会注意到的。谢谢,现在可以了!
    猜你喜欢
    • 2019-04-08
    • 2021-06-04
    • 1970-01-01
    • 2021-06-02
    • 2020-10-04
    • 2019-07-03
    • 2021-06-19
    • 2020-11-15
    • 2015-08-26
    相关资源
    最近更新 更多