All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.boot.jdbc.interceptor.DynamicDataSourceSwitchInterceptor Maven / Gradle / Ivy

The newest version!
package matrix.boot.jdbc.interceptor;

import matrix.boot.based.utils.SpringProxyUtil;
import matrix.boot.jdbc.annotation.DynamicTransactional;
import matrix.boot.jdbc.annotation.TargetDataSource;
import matrix.boot.jdbc.beans.DynamicDataSource;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.ClassUtils;

import java.lang.reflect.Method;

/**
 * @author wangcheng
 * 2021/8/19
 **/
public class DynamicDataSourceSwitchInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        Class targetClass = methodInvocation.getThis() != null ? AopUtils.getTargetClass(methodInvocation.getThis()) : null;
        Method specificMethod = ClassUtils.getMostSpecificMethod(methodInvocation.getMethod(), targetClass);
        if (!specificMethod.getDeclaringClass().equals(Object.class)) {
            final Method method = BridgeMethodResolver.findBridgedMethod(specificMethod);
            final TargetDataSource targetDataSource = SpringProxyUtil.getAnnotation(method, targetClass, TargetDataSource.class);
            if (targetDataSource != null) {
                DynamicDataSource.DynamicDataSourceHolder.switchDataSource(targetDataSource.value());
            } else {
                final DynamicTransactional dynamicTransactional = SpringProxyUtil.getAnnotation(method, targetClass, DynamicTransactional.class);
                if (dynamicTransactional != null) {
                    DynamicDataSource.DynamicDataSourceHolder.switchDataSource(dynamicTransactional.value());
                }
            }
        }
        try {
            return methodInvocation.proceed();
        } finally {
            DynamicDataSource.DynamicDataSourceHolder.clearDataSourceKey();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy