This is follow up of this Multitenancy with Spring JPA
I chose to use the \'AbstractRoutingDataSource\'. But the problem is now datasource and entitymanager bean in
I've solved similar problem. I implemented my own TenantAwareDataSource
based on Spring's AbstractDataSource
. It takes tenantId from a session-scoped bean named tenantContext. This bean is updated every time the incoming request is processed. It is done by using Spring Security's security filter:
My TenantAwareDataSource
is initialized in the startup time, but it does not matter because it is created empty - it contains no tenant datasources (e.g. pooled JDBC datasources or JPA entity manager). They are created lazily when the getConnection()
is called for the first time for the selected tenant.
So, my TenantAwareDataSource
maintains its own dynamic datasource map while AbstractRoutingDataSource
expects static initializitaion of the datasource map done in the startup time.
Read more detailed description in this article.