Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@NotNull constraint don't work for a application property value spring boot

I want to prevent a NotNull value of a application property.

In my application.yml

spring:
  security:
    oauth2:
      resourceserver:
         my-property: classpath:a/b.json

my Property class:

@Data
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class ABCProperties {

    @NotNull
    private URI myProperty

When the value of application property is empty, i don't have a constraint violation exception.

How can i prevent that the value of application property is null?

like image 862
emoleumassi Avatar asked Nov 15 '25 15:11

emoleumassi


1 Answers

You need to add @Validate to your ABCProperties as follows:

@Data
@Validated
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class ABCProperties {

    @NotNull
    private URI myProperty;
}

As a side note, as of Spring Boot 2.2, Spring finds and registers @ConfigurationProperties classes via classpath scanning. As a consequence, you do not need to annotate such classes with @Component or @Configuration or even use @EnableConfigurationProperties. If you are using a Spring Boot version that is newer than 2.2 you can remove @Configuration from your ABCProperties class.

like image 182
João Dias Avatar answered Nov 18 '25 05:11

João Dias