How to use @NotNull with spring boot?
Asked Answered
A

1

6

I have this dependency:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
</dependency>

Which have it's version managed by

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

And I have this piece:

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

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

    @NotNull
    private String urlCDI;

    //getters and setters
}

And my SpringApplication.run class has this pice:

@SpringBootApplication
@EnableConfigurationProperties
@ComponentScan({ "otherPackages", "packageWhereCollectorPropertiesIs" })

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());

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?

Algesia answered 14/8, 2018 at 0:56 Comment(0)
S
8

Add ´@Validated' annotation to your properties class

Storehouse answered 14/8, 2018 at 1:21 Comment(1)
Indeed, if I looked more carefully here I would've noticed. Thanks, now it works!Algesia

© 2022 - 2024 — McMap. All rights reserved.