我正在开发一个 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/