Spring 配置多数据源原理
要使用的技术,我们先看下annotation的定义:
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.METHOD)
- public @interface DataSource {
- String value();
- }
我们还需要实现spring的抽象类AbstractRoutingDataSource,就是实现determineCurrentLookupKey方法:
- public class DynamicDataSource extends AbstractRoutingDataSource {
- @Override
- protected Object determineCurrentLookupKey() {
- // TODO Auto-generated method stub
- return DynamicDataSourceHolder.getDataSouce();
- }
- }
- public class DynamicDataSourceHolder {
- public static final ThreadLocal<String> holder = new ThreadLocal<String>();
- public static void putDataSource(String name) {
- holder.set(name);
- }
- public static String getDataSouce() {
- return holder.get();
- }
- }
实现的核心部分,也就是AOP部分,DataSourceAspect定义如下:
- public class DataSourceAspect {
- public void before(JoinPoint point)
- {
- Object target = point.getTarget();
- String method = point.getSignature().getName();
- Class<?>[] classz = target.getClass().getInterfaces();
- Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
- .getMethod().getParameterTypes();
- try {
- Method m = classz[0].getMethod(method, parameterTypes);
- if (m != null && m.isAnnotationPresent(DataSource.class)) {
- DataSource data = m
- .getAnnotation(DataSource.class);
- DynamicDataSourceHolder.putDataSource(data.value());
- System.out.println(data.value());
- }
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- }
本文介绍如何在Spring中配置多数据源,包括通过自定义注解和AOP技术实现数据源的动态切换,以及核心组件DynamicDataSource的具体实现。
3153

被折叠的 条评论
为什么被折叠?



