cl
2026-04-17 86fd4ec5fd97081f212e4c35523ee3d44f233fb6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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);
    }
}