代码之家  ›  专栏  ›  技术社区  ›  gabriel119435

如何在spring boot中使用@NotNull?

  •  2
  • gabriel119435  · 技术社区  · 6 年前

    <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 回复  |  直到 6 年前
        1
  •  6
  •   Sébastien Helbert    6 年前

    将@Validated'批注添加到属性类