SpringBoot通过自定义注解实现多数据源
在SpringBoot中,你可以通过自定义注解和@Primary
注解来实现多数据源。以下是一个简化的例子:
- 定义数据源注解:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Qualifier
public @interface DataSource {
String value() default "";
}
- 配置数据源:
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
- 使用
@DataSource
注解来指定使用哪个数据源:
public interface DataSourceService {
@DataSource("secondary")
void secondary();
@DataSource("primary")
void primary();
}
- 创建数据源路由:
@Aspect
@Component
public class DataSourceAspect {
@Before("@annotation(dataSource)")
public void switchDataSource(JoinPoint point, DataSource dataSource) {
// 获取注解中指定的数据源名称
String dataSourceName = dataSource.value();
// 根据名称动态切换数据源
// 这里需要实现DataSourceContextHolder或类似的工具来切换数据源
DataSourceContextHolder.setDataSource(dataSourceName);
}
}
- 实现
DataSourceContextHolder
来切换数据源:
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
public static void setDataSource(String dataSourceType) {
contextHolder.set(dataSourceType);
}
public static String getDataSource() {
return contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
- 配置动态数据源:
@Configuration
public class DynamicDataSourceConfig {
@Primary
@Bean
public DataSource dynamicDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource,
@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setDefaultTargetDataSource(primaryDataSource);
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("primary", primaryDataS
评论已关闭