簡體   English   中英

map 的 map 作為 springboot 配置中的 Bean 注入?

[英]map of map as Bean injection in springboot configuration?

我通常使用 springboot 來注入 Beans 並使用類似的模式

在 application.properties 文件中

platform.accounts.acbot71.name=acbot71
platform.accounts.acbot71.secret=secret1
platform.accounts.acbot72.name=acbot72
platform.accounts.acbot72.secret=secret2

在 springboot 配置文件中

@ConfigurationProperties(prefix = "platform.accounts")
@Bean
public Map<String, PlatformAccount> platformAccounts() {
    return new TreeMap<>();
}

將 PlatformAccount 作為具有經典 getter 和 setter 的 pojo

String name;
String email;

一切正常。 但是現在,我想為現有 map 的每個值使用“內部”map 進行高級配置。我想構建一個應用程序屬性,例如..

platform.accounts.acbot71.name=acbot71
platform.accounts.acbot71.secret=secret1
platform.accounts.acbot71.subaccount1.name=sub1
platform.accounts.acbot71.subaccount1.secret=secret1
platform.accounts.acbot71.subaccount2.name=sub2
platform.accounts.acbot71.subaccount2.secret=secret2
platform.accounts.acbot72.name=acbot72
platform.accounts.acbot72.secret=secret2
platform.accounts.acbot72.subaccount1.name=sub1
platform.accounts.acbot72.subaccount1.secret=secret1

目的是向每個類型為 PlatformAccount 的 map 注入第二個 map(即第一個映射的值)

我怎樣才能做到這一點? 任何代碼作為例子?

我會改為在 application.yml 中執行此操作,並調整屬性以獲得子帳戶 map。

platform:
  accounts:
    acbot71:
      name: acbot71
      secret: secret1
      subAccounts:
        subaccount1:
          name: sub1
          secret: secret1
        subaccount2:
          name: sub2
          secret: secret2
    acbot72:
      name: acbot72
      secret: secret2
      subAccounts:
        subaccount1:
          name: sub1
          secret: secret1

我猜它在 application.properties 中看起來像這樣......

platform.accounts.acbot71.name=acbot71
platform.accounts.acbot71.secret=secret1
platform.accounts.acbot71.subAccounts.subaccount1.name=sub1
platform.accounts.acbot71.subAccounts.subaccount1.secret=secret1
platform.accounts.acbot71.subAccounts.subaccount2.name=sub2
platform.accounts.acbot71.subAccounts.subaccount2.secret=secret2
platform.accounts.acbot72.name=acbot72
platform.accounts.acbot72.secret=secret2
platform.accounts.acbot72.subAccounts.subaccount1.name=sub1
platform.accounts.acbot72.subAccounts.subaccount1.secret=secret1

您的 PlatformAccount class 可能如下所示。

public class PlatformAccount {
    private String name;
    private String secret;
    private Map<String, PlatformAccount> subAccounts;
}

我從來沒有嘗試過這樣的事情,Spring 可能會對嵌套的相同 class 感到害怕。如果是這樣,您將不得不創建一個 SubAccount 配置 class。

暫無
暫無

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

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