gabriel119435
gabriel119435

Reputation: 6802

How to use @NotNull with spring boot?

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?

Upvotes: 6

Views: 32810

Answers (1)

S&#233;bastien Helbert
S&#233;bastien Helbert

Reputation: 2210

Add ´@Validated' annotation to your properties class

Upvotes: 8

Related Questions