java - 在spring boot应用程序中根据请求 header 参数在属性文件之间动态切换

标签 java spring spring-boot

我正在开发一个 Multi-Tenancy REST spring boot 应用程序。我能够根据每个请求中的 header 值在不同的数据源之间动态切换。但我的问题出在 application.properties 文件上。不同的租户在其属性文件中对相同的属性具有不同的值。

我如何分离每个租户的属性文件,并根据请求 header 中的值动态确定要使用的属性文件

最佳答案

您不能在运行时切换配置文件。您的选择仅限于创建一个有其自身缺点的新 ApplicationContext,或者您可以在启动时加载租户属性文件并实现特定于租户的 getProperty 方法来调用需要时。

这应该处理后一种情况:

@Component
public class TenantProperties {

  private Map<String, ConfigurableEnvironment> customEnvs;

  @Inject
  public TenantProperties(@Autowired ConfigurableEnvironment defaultEnv,
      @Value("${my.tenant.names}") List<String> tenantNames) {

    this.customEnvs = tenantNames
        .stream()
        .collect(Collectors.toMap(
            Function.identity(),
            tenantId -> {
              ConfigurableEnvironment customEnv = new StandardEnvironment();
              customEnv.merge(defaultEnv);
              Resource resource = new ClassPathResource(tenantId + ".properties");

              try {
                Properties props = PropertiesLoaderUtils.loadProperties(resource);
                customEnv.getPropertySources()
                    .addLast(new PropertiesPropertySource(tenantId, props));
                return customEnv;
              } catch (IOException ex) {
                throw new RuntimeException(ex);
              }
            }));
  }

  public String getProperty(String tenantId, String propertyName) {

    ConfigurableEnvironment ce = this.customEnvs.get(tenantId);
    if (ce == null) {
      throw new IllegalArgumentException("Invalid tenant");
    }

    return ce.getProperty(propertyName);
  }
}

您需要将 my.tenant.names 属性添加到包含逗号分隔的租户名称列表(name1、name2 等)的主应用程序属性.特定于租户的属性从 name1.properties 加载,...从类路径。你明白了。

关于java - 在spring boot应用程序中根据请求 header 参数在属性文件之间动态切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147432/

相关文章:

java - switch 语句或远程调用方法

Spring Boot ActiveMQ

java - @ManyToMany 编译问题

java - 是什么导致了 Android Studio 3.1 - java.io.IOException : Failed to find byte code for javax/naming/Referenceable

java - 在 Java 中使用 SSL 调用 WS

java - 生成动态 sql SELECT 语句

java - 在 spring boot 2.4.0 版本中包含配置文件

java - 使用方法调用切入点在 Spring 中进行 AspectJ 加载时编织?

spring - 如何在 JPA 中明确声明一个实体是新的( transient 的)?

java - 使用 Apple Java 用户验证登录