【问题标题】:Spring Boot - nesting ConfigurationPropertiesSpring Boot - 嵌套 ConfigurationProperties
【发布时间】:2015-06-17 17:16:12
【问题描述】:

Spring Boot 具有许多很酷的功能。我最喜欢的是通过@ConfigurationProperties 和相应的yml/properties 文件的类型安全配置机制。我正在编写一个通过 Datastax Java 驱动程序配置 Cassandra 连接的库。我想让开发人员通过简单地编辑 yml 文件来配置 ClusterSession 对象。这在 spring-boot 中很容易。但我想允许她/他以这种方式配置多个连接。在 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

(这个sn-p来自Symfony documentation

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

【问题讨论】:

  • 我很确定你不能安全地嵌套任意数量的子对象(例如你的connections),尽管你可以声明一个Map<String,Connection> connections。如果这不起作用,也许在 GitHub 上提出功能请求。

标签: java spring spring-boot


【解决方案1】:

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

【讨论】:

  • 从 Spring Boot 1.3.0.RELEASE 开始,内部类需要是公共的,否则我得到 java.lang.IllegalAccessException: Class org.springframework.beans.BeanUtils can not access a member of class ...DatabaseProperties$Connection 带有修饰符“private”
  • 普通类(非内部类)的getter和setter如何?
  • 这些是常规的 getter 和 setter,就像在内部类中一样。如果你想设置属性primaryConnection.host,Spring 会为你调用getPrimaryConnection().setHost(value)(非常抽象,内部可能不正确)
  • 为什么在文档中定义了 PRIVATE 中的嵌套类? docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/html/…
  • 我根据你的语法定义了我的类。这些属性如何来自其他类,因为它们从外部不可见
猜你喜欢
  • 2019-08-09
  • 2017-08-21
  • 2020-01-07
  • 1970-01-01
  • 2018-02-07
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多