[英]Spring Boot - nesting ConfigurationProperties
Spring boot comes with many cool features. Spring Boot 带有许多很酷的功能。 My favourite one is a type-safe configuration mechanism through
@ConfigurationProperties
and corresponding yml/properties files.我最喜欢的是通过
@ConfigurationProperties
和相应的yml/properties 文件的类型安全配置机制。 I'm writing a library that configures Cassandra connection via Datastax Java driver.我正在编写一个通过 Datastax Java 驱动程序配置 Cassandra 连接的库。 I want to allow developers to configure
Cluster
and Session
objects by simply editing yml file.我想让开发人员通过简单地编辑 yml 文件来配置
Cluster
和Session
对象。 This is easy in spring-boot.这在 spring-boot 中很容易。 But I want to allow her/him configure multiple connections this way.
但我想允许她/他以这种方式配置多个连接。 In PHP framework - Symfony it is as easy as:
在 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?是否可以在 spring-boot 中使用 ConfigurationProperties? Should I nest them?
我应该嵌套它们吗?
You could actually use type-safe nested ConfigurationProperties
.您实际上可以使用类型安全的嵌套
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 Guide and Configuration Binding Docs .另请参阅参考指南和配置绑定文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.