Spring Boot - 嵌套ConfigurationProperties

wik*_*ikp 32 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
Run Code Online (Sandbox Code Playgroud)

(此片段来自Symfony文档)

是否可以在Spring-boot中使用ConfigurationProperties?我应该筑巢吗?

Rol*_*der 52

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

@ConfigurationProperties
public class DatabaseProperties {

    private Connection primaryConnection;

    private Connection backupConnection;

    // getter, setter ...

    public static class Connection {

        private String host;

        // getter, setter ...

    }

}
Run Code Online (Sandbox Code Playgroud)

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

如果您不想使用内部类,则可以使用注释来添加字段@NestedConfigurationProperty.

@ConfigurationProperties
public class DatabaseProperties {

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

    @NestedConfigurationProperty
    private Connection backupConnection;

    // getter, setter ...

}
Run Code Online (Sandbox Code Playgroud)

另请参见" 参考指南"和" 配置绑定文档".

  • 从Spring Boot 1.3.0.RELEASE开始,内部类需要是公共的,否则我将得到java.lang.IllegalAccessException:类org.springframework.beans.BeanUtils无法访问类的成员...带有修饰符的DatabaseProperties $ Connection “私人的” (3认同)