DataSourceAspect

邓尼茨我今天去赶集 2020年06月17日 757次浏览

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class DataSourceAspect {
    private static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 子类方法 >子类 > 父类方法1 > 父类1 > 父类方法n > 父类n >接口方法1 > 接口1 > 接口方法n > 接口n
     *
     * @param point
     */
    public void before(JoinPoint point) {

        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?> clazz = target.getClass();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
        try {
            //类层获取数据源
            String dataSourceKey = getDataSourceKey(method, clazz, parameterTypes);
            //接口层获取数据源
            if (StringUtils.isEmpty(dataSourceKey) && interfaces.length > 0) {
                clazz = interfaces[0];
                dataSourceKey = getDataSourceKey(method, clazz, parameterTypes);
            }
            //设置数据源
            if (StringUtils.isEmpty(dataSourceKey)) {
                dataSourceKey = DataSource.HBOM_SERVICE;
            }
            DataSourceHolder.putDataSourceKey(dataSourceKey);
        } catch (Exception e) {
            logger.error("DataSourceAspect before error:" + e.getMessage());
        }
    }

    private String getDataSourceKey(String method, Class<?> clazz, Class<?>[] parameterTypes) {
        String dataSourceKey = null;
        for (; clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                Method methodClz = clazz.getDeclaredMethod(method, parameterTypes);
                if (methodClz.isAnnotationPresent(DataSource.class)) {
                    dataSourceKey = methodClz.getAnnotation(DataSource.class).value();
                    break;
                }
                if (clazz.isAnnotationPresent(DataSource.class)) {
                    dataSourceKey = clazz.getAnnotation(DataSource.class).value();
                    break;
                }
            } catch (Exception e) {
            }
        }
        return dataSourceKey;
    }
}