Spring Boot - nesting ConfigurationProperties

后端 未结 1 1751
一整个雨季
一整个雨季 2021-01-31 08:12

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

1条回答
  •  [愿得一人]
    2021-01-31 08:34

    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.

    0 讨论(0)
提交回复
热议问题