Member-only story
Multi Tenancy in Spring Boot
In the previous post — https://medium.com/@abdulrahmanka/multi-tenancy-approach-in-postgresql-be5005697494, I had mentioned how to isolate and provide multi tenancy in Postgres. Now this need to tied up with a backend system like Spring Boot to bring the data isolation to the API’s to fully use the approach.
Identify the client context
Use the API URI to capture the client id. Capture the client id as part of the path param
@RequestMapping("/{clientId}/account")
Set the client Id to Thead Local
Here the client Id will be added to thread local so that its available through out the request session.
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TenantIdentifierInterceptor implements HandlerInterceptor {
public static final ThreadLocal<String> currentTenant = new ThreadLocal<>();
public static final ThreadLocal<String> asyncTenant = new ThreadLocal<>();
@Value("${server.servlet.context-path}")
private String contextPath;
private String clientIdFromUri(String uri, String contextPath) throws…