package com.huigou.topsun.dataSource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Slf4j
public class DataSourceAspect {

    /**
     * 在dao层方法获取datasource对象之前，在切面中指定当前线程数据源
     */
    public void before(JoinPoint point) {
        Class<?>[] parameterTypes = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes();
        Method method = null;
        try {
            method = point.getTarget().getClass().getDeclaredMethod(point.getSignature().getName(), parameterTypes);
            if (method != null && method.isAnnotationPresent(DataSource.class)) {
                DataSource data = method.getAnnotation(DataSource.class);
                log.debug("用户选择数据库库类型： {}", data.value());
                HandleDataSource.putDataSource(data.value()); // 数据源放到当前线程中
            }
        } catch (Exception e) {
            log.error("aop分配数据源异常", e);
        }
    }
    public void after(JoinPoint joinPoint) throws Throwable {
        HandleDataSource.removeDataSource();
    }

}