Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Elegant Dynamic Data Source Switching in Spring Boot with ThreadLocal & AbstractRoutingDataSource

This tutorial demonstrates how to implement dynamic data source switching in Spring Boot using ThreadLocal and AbstractRoutingDataSource, covering configuration, annotation-based switching via AOP, and runtime data source registration from a database.

Introduction

The author needed to fetch data from different databases and write to the current database, requiring dynamic data source switching. After the MyBatis-Plus dynamic-datasource-spring-boot-starter failed due to environment issues, they implemented a custom solution using ThreadLocal and AbstractRoutingDataSource to mimic the starter's thread-level data source routing.

Core Concepts

ThreadLocal

ThreadLocal

provides thread-local variables. Each thread accesses its own copy, ensuring isolation and reducing synchronization overhead. The article notes two key points: (1) ThreadLocal shares data within a thread but isolates across threads; (2) Internally, it stores values in a map keyed by the current thread instance.

AbstractRoutingDataSource

This Spring class selects a data source based on user-defined rules. Before each query, its abstract method determineCurrentLookupKey() is invoked to decide which data source to use.

Environment

Spring Boot 2.4.8

MyBatis-Plus 3.2.0

Druid 1.2.6

Lombok 1.18.20

commons-lang3 3.10

Implementation Steps

2.1 ThreadLocal Holder

public class DataSourceContextHolder {
    private static final ThreadLocal<String> DATASOURCE_HOLDER = new ThreadLocal<>();

    public static void setDataSource(String dataSourceName) {
        DATASOURCE_HOLDER.set(dataSourceName);
    }

    public static String getDataSource() {
        return DATASOURCE_HOLDER.get();
    }

    public static void removeDataSource() {
        DATASOURCE_HOLDER.remove();
    }
}

2.2 DynamicDataSource Extending AbstractRoutingDataSource

public class DynamicDataSource extends AbstractRoutingDataSource {
    public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultDataSource);
        super.setTargetDataSources(targetDataSources);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }
}

The constructor sets the default data source and a map of target data sources (key = data source name, value = DataSource).

2.3 Data Source Configuration

Two data sources (master and slave) are defined in application.yml using Druid. A configuration class creates the data source beans and registers the DynamicDataSource as the primary bean:

@Configuration
public class DateSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource slaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource createDynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>();
        DataSource defaultDataSource = masterDataSource();
        dataSourceMap.put("master", defaultDataSource);
        dataSourceMap.put("slave", slaveDataSource());
        return new DynamicDataSource(defaultDataSource, dataSourceMap);
    }
}

2.4 Testing

Two test databases each contain a test_user table with a user_name column. Master holds 'master', slave holds 'slave'. A controller method accepts a data source name, sets it via DataSourceContextHolder.setDataSource(), queries via MyBatis-Plus, then removes the holder. Results confirm switching works.

Note: Exclude Spring Boot's auto-configuration to avoid circular dependency:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Optimization

2.5.1 Annotation-Based Switching

To avoid repetitive boilerplate, a @DS annotation and an AOP aspect are introduced.

Annotation Definition

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DS {
    String value() default "master";
}

AOP Aspect

@Aspect
@Component
@Slf4j
public class DSAspect {
    @Pointcut("@annotation(com.jiashn.dynamic_datasource.dynamic.aop.DS)")
    public void dynamicDataSource() {}

    @Around("dynamicDataSource()")
    public Object datasourceAround(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DS ds = method.getAnnotation(DS.class);
        if (Objects.nonNull(ds)) {
            DataSourceContextHolder.setDataSource(ds.value());
        }
        try {
            return point.proceed();
        } finally {
            DataSourceContextHolder.removeDataSource();
        }
    }
}

The aspect reads the annotation value, sets the data source before proceeding, and cleans up in a finally block. Default is "master", so only slave methods need explicit @DS("slave").

2.5.2 Dynamic Data Source Addition at Runtime

Business requirement: load additional data sources from a database table at startup.

Data Source Entity

@Data
@Accessors(chain = true)
public class DataSourceEntity {
    private String url;
    private String userName;
    private String passWord;
    private String driverClassName;
    private String key;
}

Enhanced DynamicDataSource

The class now holds a reference to the target data source map and exposes a createDataSource method:

@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    private final Map<Object, Object> targetDataSourceMap;

    public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultDataSource);
        super.setTargetDataSources(targetDataSources);
        this.targetDataSourceMap = targetDataSources;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSource();
    }

    public void createDataSource(List<DataSourceEntity> dataSources) {
        try {
            if (CollectionUtils.isNotEmpty(dataSources)) {
                for (DataSourceEntity ds : dataSources) {
                    Class.forName(ds.getDriverClassName());
                    DriverManager.getConnection(ds.getUrl(), ds.getUserName(), ds.getPassWord());
                    DruidDataSource dataSource = new DruidDataSource();
                    BeanUtils.copyProperties(ds, dataSource);
                    dataSource.setTestOnBorrow(true);
                    dataSource.setTestWhileIdle(true);
                    dataSource.setValidationQuery("select 1");
                    dataSource.init();
                    this.targetDataSourceMap.put(ds.getKey(), dataSource);
                }
                super.setTargetDataSources(this.targetDataSourceMap);
                super.afterPropertiesSet();
                return;
            }
        } catch (ClassNotFoundException | SQLException e) {
            log.error("---程序报错---:{}", e.getMessage());
        }
    }

    public boolean existsDataSource(String key) {
        return Objects.nonNull(this.targetDataSourceMap.get(key));
    }
}

The map is initialized from the configuration class. createDataSource validates connectivity, creates a DruidDataSource, sets pool validation properties, initializes it, adds to the map, then refreshes the target data sources and calls afterPropertiesSet() to register them.

Loading from Database on Startup

A test_db_info table stores data source details. A CommandLineRunner bean reads the table, maps to DataSourceEntity list, and invokes dynamicDataSource.createDataSource().

@Component
public class LoadDataSourceRunner implements CommandLineRunner {
    @Resource
    private DynamicDataSource dynamicDataSource;
    @Resource
    private TestDbInfoMapper testDbInfoMapper;

    @Override
    public void run(String... args) throws Exception {
        List<TestDbInfo> testDbInfos = testDbInfoMapper.selectList(null);
        if (CollectionUtils.isNotEmpty(testDbInfos)) {
            List<DataSourceEntity> ds = new ArrayList<>();
            for (TestDbInfo testDbInfo : testDbInfos) {
                DataSourceEntity sourceEntity = new DataSourceEntity();
                BeanUtils.copyProperties(testDbInfo, sourceEntity);
                sourceEntity.setKey(testDbInfo.getName());
                ds.add(sourceEntity);
            }
            dynamicDataSource.createDataSource(ds);
        }
    }
}

After startup, the dynamically added data source (e.g., "add_slave") is available for switching via the same @DS annotation or manual holder calls.

Conclusion

The article provides a complete, step-by-step guide to building a flexible dynamic data source routing mechanism in Spring Boot, from basic ThreadLocal/AbstractRoutingDataSource integration to annotation-driven switching and runtime data source registration. The approach mirrors the MyBatis-Plus starter's design while remaining lightweight and customizable. Source code is available at github.com/lovejiashn/… .

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaAOPSpring BootDynamic Data SourceMyBatis-PlusThreadLocalDruidAbstractRoutingDataSource

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion