Spring Boot - nesting ConfigurationProperties

JavaSpringSpring Boot

Java Problem Overview


Spring boot comes with many cool features. My favourite one is a type-safe configuration mechanism through @ConfigurationProperties and corresponding yml/properties files. I'm writing a library that configures Cassandra connection via Datastax Java driver. I want to allow developers to configure Cluster and Session objects by simply editing yml file. This is easy in spring-boot. But I want to allow her/him configure multiple connections this way. In PHP framework - Symfony it is as easy as:

doctrine:
  dbal:
    default_connection: default
    connections:
      default:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
      customer:
        driver:   "%database_driver2%"
        host:     "%database_host2%"
        port:     "%database_port2%"
        dbname:   "%database_name2%"
        user:     "%database_user2%"
        password: "%database_password2%"
        charset:  UTF8

(this snippet comes from Symfony documentation)

Is it possible in spring-boot using ConfigurationProperties? Should I nest them?

Java Solutions


Solution 1 - Java

You could actually use type-safe nested ConfigurationProperties.

@ConfigurationProperties
public class DatabaseProperties {
    
    private Connection primaryConnection;
    
    private Connection backupConnection;
    
    // getter, setter ...
    
    public static class Connection {

        private String host;

        // getter, setter ...

    }
    
}

Now you can set the property primaryConnection.host.

If you don't want to use inner classes then you can annotate the fields with @NestedConfigurationProperty.

@ConfigurationProperties
public class DatabaseProperties {
    
    @NestedConfigurationProperty
    private Connection primaryConnection; // Connection is defined somewhere else
    
    @NestedConfigurationProperty
    private Connection backupConnection;
    
    // getter, setter ...
    
}

See also the Reference Guide and Configuration Binding Docs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwikpView Question on Stackoverflow
Solution 1 - JavaRoland WeislederView Answer on Stackoverflow