0

I'm trying to get a Map with {"host1": DatabaseConfigurationProperty("abcd", "mytable", "user")}, however my below code only generates an empty Map.

application.yml:

database:
  host1:
    hostname: abcd
    name: mytable
    username: user

DatabaseConfigurationProperty.java:

@Configuration
@ConfigurationProperties("database")
@EnableConfigurationProperties
@Component
public class DatabaseConfigurationProperty {
    Map<String, DatabaseConfiguration> database = new HashMap<>();

    public Map<String, DatabaseConfiguration> getDatabase() {
        return database;
    }

    public void setDatabase(Map<String, DatabaseConfiguration> database) {
        this.database = database;
    }
}

DatabaseConfiguration.java:

public class DatabaseConfiguration {
    String host;
    String name;
    String username;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

MainConfig.java:

@Configuration
public class MainConfig {

    @Autowired
    private DatabaseConfigurationProperty databaseConfigurationProperty;

}

databaseConfigurationProperty.getDatabase() is returning as an empty Map.

onepiece
  • 3,279
  • 8
  • 44
  • 63

1 Answers1

0

With @ConfigurationProperties("database") you are telling spring to map values under property database in yaml to the fields in your class DatabaseConfigurationProperty.

Hence DatabaseConfigurationProperty is expecting a field named database under database in yaml like

database: database: host1: hostname: abcd name: mytable username: user

If you have your yaml in this format, your example will work fine.

One other option you have is to let the yaml remain same and change

@ConfigurationProperties("database") to `@ConfigurationProperties`

Then the class would expect field database at top level which is present in your yaml already.

You also have to correct the field name host to hostname in DatabaseConfiguration or change the yaml property to match the names.

harsh
  • 1,471
  • 13
  • 12
  • Is there a way to only autowire the `DatabaseConfiguration` for `host1`? Like if I ran the code with `-Ddatabase=host1`. – onepiece Oct 19 '18 at 21:05