簡體   English   中英

如果未在application.properties中顯式設置鍵,是否不可能通過環境變量“覆蓋” Spring屬性?

[英]Is it not possible to “override” Spring properties through environment variable if the key are not explicitly set in application.properties?

我有一個具有SSL通用屬性的Springboot2應用程序,如下所示

    @Conditional(when = "enabled", verify = "truststore != null || trustAnyCertificate", message = "Can't enable TLS without trust policy.")
    @Conditional(when = "enabled && mutual", verify = "keystore != null", message = "Can't enable mutual TLS without a keystore.")
    @Conditional(when = "enabled && trustAnyCertificate", verify = "truststore == null", message = "Can't enable TLS with trust policy collision between truststore and trustAll.")
    public class TLSProperties {

        /** enabled. */
        @Builder.Default
        private boolean enabled = true;
        /** mutual. */
        @Builder.Default
        private boolean mutual = true;
        /** hostname verification. */
        @Builder.Default
        private boolean allowAnyHostname = false;
        /** trust any certificate. */
        @Builder.Default
        private boolean trustAnyCertificate = false;

        @Builder.Default
        private String algorithm = "TLSv1.2";

        /** truststore. */
        @Valid
        private CertificateProperties truststore;
        /** keystore. */
        @Valid
        private CertificateProperties keystore;
    }

@Conditional自定義批注的作用是,如果when條件的評估結果為true,它將檢查verify條件是否也評估為true,如果不是,它將在啟動時引發異常。

CertificateProperties對象如下

    public class CertificateProperties {

        /** path. */
        @File
        private String path;
        /** password. */
        @NotEmpty
        private String password;
        /** keystore type (JKS, PKCS12). */
        @Builder.Default
        private KeystoreTypeEnum type = KeystoreTypeEnum.JKS;
    }

現在取決於ENV我可以有tls.trustAnyCertificate=true沒有tls.truststore定義,它是由自定義驗證@Conditional財產

否則我需要tls.truststore.pathtls.truststore.password因為@Conditional會強制我將truststore設置為非null,並且CertificateProperties對象會強制我具有路徑和密碼( @File注釋會驗證該屬性不是null,是現有文件和可訪問文件的路徑。

在我的開發環境中,這很容易,我用開發配置文件啟動了我的應用程序,並使用tls.trustAnyCertificate=trueapplication-dev.properties定義了這些屬性。在我的產品環境中,我正在使用docker,並且沒有彈簧地啟動應用程序配置文件,因此僅掃描application.property文件。 但是,對於在application.properties文件中未顯式設置的屬性(具有空值),我無法使用替代方法。

如果我在application.properties設置tls.truststore.path=null ,則可以在prod中使用env變量很好地覆蓋它,並且可以正常工作。 但是現在在我的開發環境中,由於我使用trustall屬性,因此我不再需要信任trustall ,Spring將檢測到信任庫不為null,因此將對其進行驗證,並且由於path和pass不能為null引發錯誤。

即使沒有在屬性文件中顯式設置鍵,我也可以讓Spring使用屬性值作為env變量嗎?

當您要為“ dev”配置文件設置值時,可以僅為該配置文件創建屬性文件。 除了prod的application.properties外,還可以創建application-dev.properties。

application-dev.properties將僅保留激活“ dev”配置文件時使用的值。

application.properties

tls.truststore.path=/prod/path

application-dev.properties

tls.truststore.path=/dev/path

暫無
暫無

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

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