spring boot应用中根据请求头参数动态切换属性文件

bru*_*yne 6 java spring spring-boot

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

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

And*_*own 2

您无法在运行时切换配置文件。您的选择仅限于创建一个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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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