Layered Interoperability with Spring Security JPA

This is a continuation of this multi-specification with Spring JPA

I decided to use "AbstractRoutingDataSource". But now the problem is the datasource and entitymanager bean are initialized on startup. is there a way to configure this in Spring, how will it initialize after user authentication?

Another problem I can think of would be how to handle concurrency. I put tenantId in this class

public class ThreadLocalContextUtil {
 private static final ThreadLocal<String> contextHolder =
            new ThreadLocal<String>();

   public static void setTenantId(String tenantId) {
      Assert.notNull(tenantId, "customerType cannot be null");
      contextHolder.set(tenantId);
   }

   public static String getTenantId() {
      return (String) contextHolder.get();
   }

   public static void clearTenant() {
      contextHolder.remove();
   }
}

      

The solution I can think of would be to remove the tenantId after the datasource is initialized. it is right?

+3


source to share


1 answer


I have solved a similar problem. I have implemented my own TenantAwareDataSource

based on Spring AbstractDataSource

. It takes tenantId from a bean with session> named tenantContext . This bean is updated every time an incoming request is processed. This is done using the Spring Security security filter:

<security:http auto-config='false' >
    <security:custom-filter before="FIRST" ref="tenantFilter" />
    <!-- ...more security stuff... -->
</security:http>

      

My is TenantAwareDataSource

initialized at startup, but it doesn't matter because it is created empty - it does not contain tenant data sources (such as JDBC federated data sources or JPA entity manager). They are created lazily the getConnection()

first time they are called for the selected tenant.



So my TenantAwareDataSource

maintains its own dynamic data map, while it AbstractRoutingDataSource

expects a static data map initialization done at startup.

Read more about this in the article .

+3


source







All Articles