Spring Boot - 嵌套ConfigurationProperties

时间:2015-04-12 08:51:54

标签: java spring spring-boot

Spring boot具有许多很酷的功能。我最喜欢的是通过@ConfigurationProperties和相应的yml / properties文件的类型安全配置机制。我正在编写一个通过Datastax Java驱动程序配置Cassandra连接的库。我想让开发人员只需编辑yml文件即可配置ClusterSession个对象。弹簧靴很容易。但我希望允许她/他以这种方式配置多个连接。在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?我应该筑巢吗?

1 个答案:

答案 0 :(得分:44)

您实际上可以使用类型安全的嵌套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 GuideConfiguration Binding Docs