首先是spring-dao.xml
其次是四个class
1. DataSource
package com.ssm.dataorigin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String value();
}
2. DataSourceAspect
package com.ssm.dataorigin;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
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
}
}
}
3. DynamicDataSource
package com.ssm.dataorigin;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSouce();
}
}
4. DynamicDataSourceHolder
package com.ssm.dataorigin;
public class DynamicDataSourceHolder {
public static final ThreadLocalholder = new ThreadLocal();
public static void putDataSource(String name) {
holder.set(name);
}
public static String getDataSouce() {
return holder.get();
}
}
使用时 在Mapper方法上加注解 @DataSource 来确定要使用的源 默认源不用注解
public interface AudioModelMapper {
public ListgetAudioModelActual(AudioModel am);
@DataSource("robotoa")
public ListselectOa();
}