Spring 引导 - 嵌套 ConfigurationProperties

Spring Boot - nesting ConfigurationProperties

Spring 引导具有许多很酷的功能。我最喜欢的是通过 @ConfigurationProperties 和相应的 yml/properties 文件的类型安全配置机制。我正在编写一个库,通过 Datastax Java 驱动程序配置 Cassandra 连接。我想让开发人员通过简单地编辑 yml 文件来配置 ClusterSession 对象。这在 spring-boot 中很容易。但是我想允许 her/him 以这种方式配置多个连接。在 PHP 框架 - Symfony 中,它非常简单:

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

(此片段来自 Symfony documentation

是否可以在 spring-boot 中使用 ConfigurationProperties?我应该嵌套它们吗?

你实际上可以使用类型安全的嵌套 ConfigurationProperties.

@ConfigurationProperties
public class DatabaseProperties {

    private Connection primaryConnection;

    private Connection backupConnection;

    // getter, setter ...

    public static class Connection {

        private String host;

        // getter, setter ...

    }

}

现在您可以设置 属性 primaryConnection.host.

如果你不想使用内部 类 那么你可以用 @NestedConfigurationProperty.

注释字段
@ConfigurationProperties
public class DatabaseProperties {

    @NestedConfigurationProperty
    private Connection primaryConnection; // Connection is defined somewhere else

    @NestedConfigurationProperty
    private Connection backupConnection;

    // getter, setter ...

}

另见 Reference Guide and Configuration Binding Docs