简体   繁体   中英

@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?

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.

When you have nested objects which fields must be validated, you need add @Valid to that nested object class member declaration:

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

    @Valid
    private MyComplicatedProps myProperty;

    @Data
    public static class MyComplicatedProps {
        @NotNull
        private URI uri;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM