原来项目用的spring声明式事务处理 现在需要加上mysql的读写库 应用层使用的是aop切换数据库连接 但是读的时候有时候是读库 有时候是写库 不知道是否和声明式事务处理有关 各位大大帮忙看看
applicationContext.xml
<.....省略配置>
<.....省略配置>
<!-- write -->
<!-- read -->
<...省略...>
/tx:attributes
/tx:advice
aop:config
/aop:aspect
/aop:config
spring aop 动态选取
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String value();
}
多数据源
public class ChooseDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return HandleDataSource.getDataSource();
}
}
ThreadLocal
public class HandleDataSource {
public static final ThreadLocal<String> holder = new ThreadLocal<String>();
public static void putDataSource(String datasource) {
holder.set(datasource);
}
public static String getDataSource() {
return holder.get();
}
}
切面类
public class DataSourceAspect {
public void pointCut(){};
public void before(JoinPoint point)
{
Object target = point.getTarget();
System.out.println(target.toString());
String method = point.getSignature().getName();
System.out.println(method);
Class<?>[] classz = target.getClass().getInterfaces();
Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes();
try {
Method m = classz[0].getMethod(method, parameterTypes);
System.out.println(m.getName());
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource data = m.getAnnotation(DataSource.class);
HandleDataSource.putDataSource(data.value());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
接着在service的接口类上
@DataSource("read")
public List<Page>findForIndex();
结果有时候是用read有时候用write 有没有人给点建议 谢谢了