ConfigurationProperties

ConfigurationProperties

本文介绍了Spring Boot-嵌套ConfigurationProperties的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Boot具有许多很酷的功能.我最喜欢的一种是通过和相应的yml/properties文件.我正在编写一个通过Datastax Java驱动程序配置Cassandra连接的库.我想允许开发人员通过简单地编辑yml文件来配置ClusterSession对象.在春季启动时这很容易.但我想允许他/他以这种方式配置多个连接.在PHP框架-Symfony中,它非常简单:

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:

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文档)

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

Is it possible in spring-boot using ConfigurationProperties? Should I nest them?

推荐答案

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

You could actually use type-safe nested 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注释字段.

If you don't want to use inner classes then you can annotate the fields with @NestedConfigurationProperty.

@ConfigurationProperties
public class DatabaseProperties {

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

    @NestedConfigurationProperty
    private Connection backupConnection;

    // getter, setter ...

}

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

这篇关于Spring Boot-嵌套ConfigurationProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 17:30