簡體   English   中英

@NotNull 約束不適用於應用程序屬性值 spring 啟動

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

我想阻止應用程序屬性的 NotNull 值。

在我的 application.yml

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

我的財產 class:

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

    @NotNull
    private URI myProperty

當應用程序屬性的值為空時,我沒有約束違反異常。

如何防止應用程序屬性的值為 null?

您需要將@Validate添加到您的ABCProperties ,如下所示:

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

    @NotNull
    private URI myProperty;
}

附帶說明一下,從 Spring Boot 2.2 開始,Spring 通過類路徑掃描找到並注冊@ConfigurationProperties類。 因此,您不需要使用@Component@Configuration注釋此類類,甚至不需要使用@EnableConfigurationProperties 如果您使用的是高於 2.2 的 Spring 引導版本,您可以從ABCProperties class 中刪除@Configuration

當您有嵌套的對象時,必須驗證哪些字段,您需要將@Valid添加到該嵌套的 object class 成員聲明中:

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

    @Valid
    private MyComplicatedProps myProperty;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM