Java Spring Boot - 嵌套 ConfigurationProperties
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29587640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot - nesting ConfigurationProperties
提问by wikp
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 writing a library that configures Cassandra connection via Datastax Java driver. I want to allow developers to configure Cluster
and Session
objects by simply editing yml file. This is easy in spring-boot. But I want to allow her/him configure multiple connections this way. In PHP framework - Symfony it is as easy as:
Spring Boot 具有许多很酷的功能。我最喜欢的是通过@ConfigurationProperties
yml/properties 文件实现类型安全的配置机制。我正在编写一个通过 Datastax Java 驱动程序配置 Cassandra 连接的库。我想让开发人员通过简单地编辑 yml 文件来配置Cluster
和Session
对象。这在 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
(this snippet comes from Symfony documentation)
(此片段来自Symfony 文档)
Is it possible in spring-boot using ConfigurationProperties? Should I nest them?
是否可以在 spring-boot 中使用 ConfigurationProperties?我应该嵌套它们吗?
采纳答案by Roland Weisleder
You could actually use type-safe nested ConfigurationProperties
.
您实际上可以使用类型安全的 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
.
现在您可以设置属性primaryConnection.host
。
If you don't want to use inner classes then you can annotate the fields with @NestedConfigurationProperty
.
如果您不想使用内部类,那么您可以使用@NestedConfigurationProperty
.
@ConfigurationProperties
public class DatabaseProperties {
@NestedConfigurationProperty
private Connection primaryConnection; // Connection is defined somewhere else
@NestedConfigurationProperty
private Connection backupConnection;
// getter, setter ...
}
See also the Reference Guideand Configuration Binding Docs.