it.drive.view
it.drive.view

Reputation: 115

map of map as Bean injection in springboot configuration?

i usually use springboot to inject Beans and use patterns like

in a application.properties file

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

in a springboot configuration file

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

with PlatformAccount as a pojo with classic getters and setters

String name;
String email;

All is ok. But now, i'd like to do an advanced configuration with 'inner' map for each value of the existing map. I'd like to build an application properties like..

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

Purpose is to inject a second map into each object of type PlatformAccount (i.e. the value of the first map)

How can i do that ? any code as example ?

Upvotes: 0

Views: 112

Answers (1)

warmCabin
warmCabin

Reputation: 139

I'd do it in application.yml instead, and tweak the properties to have a subAccounts 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

I guess it would look like this in 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

And your PlatformAccount class could look like this.

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

I've never tried anything like this, Spring might freak out about the nested identical class. If it does, you would have to make a SubAccount config class.

Upvotes: 1

Related Questions