我有使用 application.yml 進行配置的 spring boot 應用程式。結構類似于:
...
rmq:
host: "host"
port: 5672
...
在我的代碼中,我有 ApplicationConfig 類,如下所示:
@AllArgsConstructor
class ApplicationConfig {
private RabbitConfig rabbitConfig;
}
@ConfigurationProperties(prefix = "rmq")
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}
問題是 rmq 部分在我的應用程式中是可選的。我希望欄位 rabbitConfig 將由 null 初始化,以防它在 application.yml 中不存在。
但實際上,如果我在組態檔中洗掉 rmq 部分,則會出現錯誤(rmq.host 不存在)。在這種情況下,是否可以強制 springboot 用 null 初始化 rabbitConfig?
uj5u.com熱心網友回復:
您可以@ConditionalOnProperty用于此類情況。在您的情況下,您應該將其定義為:
@ConfigurationProperties(prefix = "rmq")
@ConditionalOnProperty(prefix = "rmq", name = "host", matchIfMissing = true)
class RabbitConfig {
@NotNull
private String host;
@NotNull
private Integer port;
}
然后它只會在有rmq.host設定的情況下加載 bean,如果沒有,它將被設定為null.
還有一個替代方案,你總是把即 rmq.enabled = true | 假的,然后@ConditionalOnProperty(prefix = "rmq", name = "host", havingValue = true)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530908.html
標籤:春天弹簧靴配置
