package com.vincent.rsf.server.common.datasource;
|
|
import org.aspectj.lang.ProceedingJoinPoint;
|
import org.aspectj.lang.annotation.Around;
|
import org.aspectj.lang.annotation.Aspect;
|
import org.aspectj.lang.reflect.MethodSignature;
|
import org.springframework.core.Ordered;
|
import org.springframework.core.annotation.Order;
|
import org.springframework.stereotype.Component;
|
|
import java.lang.reflect.Method;
|
|
/**
|
* 注解数据源切换
|
*/
|
@Aspect
|
@Component
|
@Order(Ordered.HIGHEST_PRECEDENCE + 20)
|
public class UseDataSourceAspect {
|
|
@Around("@annotation(com.vincent.rsf.server.common.datasource.UseDataSource) || @within(com.vincent.rsf.server.common.datasource.UseDataSource)")
|
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
UseDataSource useDataSource = resolveAnnotation(joinPoint);
|
if (useDataSource == null) {
|
return joinPoint.proceed();
|
}
|
DataSourceContextHolder.push(useDataSource.value());
|
try {
|
return joinPoint.proceed();
|
} finally {
|
DataSourceContextHolder.poll();
|
}
|
}
|
|
private UseDataSource resolveAnnotation(ProceedingJoinPoint joinPoint) {
|
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
Method method = signature.getMethod();
|
UseDataSource annotation = method.getAnnotation(UseDataSource.class);
|
if (annotation != null) {
|
return annotation;
|
}
|
Class<?> targetClass = joinPoint.getTarget().getClass();
|
return targetClass.getAnnotation(UseDataSource.class);
|
}
|
}
|