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

com.github.dennisit.vplus.data.dsource.multi.MultipleDataSourceAspect Maven / Gradle / Ivy

There is a newer version: 2.0.8
Show newest version
package com.github.dennisit.vplus.data.dsource.multi;

import com.github.dennisit.vplus.data.dsource.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Slf4j
public class MultipleDataSourceAspect {

    public Object doAround(ProceedingJoinPoint jp) throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("MultipleDataSourceAspectAdvice invoked!");
        }

        Signature signature = jp.getSignature();
        String dataSourceKey = getDataSourceKey(signature);

        if (StringUtils.hasText(dataSourceKey)) {
            MultipleDataSource.setDataSourceKey(dataSourceKey);
        }

        Object jpVal = jp.proceed();

        return jpVal;
    }

    public String getDataSourceKey(Signature signature) {
        if (null == signature) {
            return null;
        }

        if (signature instanceof MethodSignature) {

            //检测方法级注解
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(DataSource.class)) {
                return dsSettingInMethod(method);
            }

            //类级注解
            Class declaringClazz = method.getDeclaringClass();
            if (declaringClazz.isAnnotationPresent(DataSource.class)) {
                try {
                    return dsSettingInConstructor(declaringClazz);
                } catch (Exception e) {
                    log.error("获取构造方法的DataSource注解失败", e);
                }
            }

            //包级注解,为了配置方便,包注解和类以及方法注解方式不同
            Package pkg = declaringClazz.getPackage();
            return dsSettingInPackage(pkg);

        }

        return null;
    }

    private String dsSettingInMethod(Method method) {
        DataSource dataSource = method.getAnnotation(DataSource.class);
        return dataSource.value();
    }

    private String dsSettingInConstructor(Class clazz) {
        DataSource dataSource = (DataSource) clazz.getAnnotation(DataSource.class);
        return dataSource.value();
    }

    private String dsSettingInPackage(Package pkg) {
        return MultipleDataSource.getPackageDataSource(pkg.getName());
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy