首页 > 解决方案 > 在嵌套地图中重用弹簧配置属性

问题描述

我有一个支持多租户的 Spring Boot 应用程序。我希望支持一组自定义配置属性的全局和每租户配置。对于每个属性,可以配置一个全局值,但对于特定租户,该值可能会被覆盖。

目前我只有全局属性,使用一些用@ConfigurationProperties. 例如

    @ConfigurationProperties("props1")
    class Props1 {
        ...
    }

    @ConfigurationProperties("props2")
    class Props2 {
        ...
    }

    @ConfigurationProperties("props3")
    class Props3 {
        ...
    }

我希望能够像这样配置属性:

props1.a=...
props1.b=...

props2.x=...
props2.y=...

props3.z=...

tenant.some-tenant-id.props1.b=...
tenant.some-tenant-id.props3.z=...

tenant.some-other-tenant-id.props2.x=...

我正在考虑添加另一个@ConfigurationProperties类,例如前缀tenant和每个现有类 a Map,其中键将是租户名称,例如:

@ConfigurationProperties("tenant")
class TenantSpecificProps {
   private Map<String, Props1> props1;
   private Map<String, Props2> props2;
   private Map<String, Props3> props3;
   ...
}

但是我担心重用@ConfigurationProperties为地图注解的类可能会在以后导致问题,因为这不是在 Spring 中使用这些类的正常方式。此外,我需要手动合并全局值和每个租户值(每个租户覆盖全局值)。

这是一种有效的方法,和/或有更惯用的方法吗?

标签: javaspringspring-boot

解决方案


推荐阅读