java / expert
Snippet
Dynamic Multi-Tenancy Routing with AbstractRoutingDataSource
This expert-level pattern allows a Spring application to switch between multiple data sources at runtime based on a lookup key (e.g., a Tenant ID from a ThreadLocal). It is essential for SaaS architectures where data isolation is required at the database level.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TenantRoutingDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return TenantContext.getCurrentTenant();}}@Configurationpublic class DataSourceConfig {@Beanpublic DataSource dataSource() {TenantRoutingDataSource routingDataSource = new TenantRoutingDataSource();Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("TENANT_A", tenantADataSource());targetDataSources.put("TENANT_B", tenantBDataSource());routingDataSource.setTargetDataSources(targetDataSources);routingDataSource.setDefaultTargetDataSource(defaultDataSource());return routingDataSource;}}
spring
Breakdown
1
extends AbstractRoutingDataSource
Inherits from Spring's internal routing mechanism for dynamic data source resolution.
2
determineCurrentLookupKey()
The core logic that Spring calls before every query to decide which database to use.
3
setTargetDataSources(targetDataSources)
Registers a map of available data sources associated with their respective lookup keys.