飞哥的海

导航

sprinboot 通过@Aspect 获取接口上的注解, 若依改造为mybatis-plus,并支持多数据源

0.在springboot的AOP实践过程种,发现 @Pointcut 切点并不能获取接口上的注解
1.在多次尝试后,可以在实现了,多数据源绑定到mapper interfac层.
2.以下代码ruoyi开源框架的代码做的修改,我将其改造为mybatis-plus版,并且支持多数据源.

 

 

/**
 * 多数据源处理
 * 
 * @author ruoyi
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect
{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
            + "|| @within(com.ruoyi.common.annotation.DataSource)"
            + "|| target(com.baomidou.mybatisplus.core.mapper.BaseMapper)")
    public void dsPointCut()
    {

    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable
    {
        DataSource dataSource = getDataSource(point);

        if (StringUtils.isNotNull(dataSource))
        {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }

        try
        {
            return point.proceed();
        }
        finally
        {
            // 销毁数据源 在执行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    /**
     * 获取需要切换的数据源
     */
    public DataSource getDataSource(ProceedingJoinPoint point) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        if (Objects.nonNull(dataSource))
        {
            return dataSource;
        }
        dataSource = AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
        if (Objects.nonNull(dataSource))
        {
            return dataSource;
        }

        Class<?> targetClass=point.getTarget().getClass();
        Object[] targetClassInterfaceList = targetClass.getInterfaces();
        Object targetClassInterface = targetClassInterfaceList[0];
        dataSource = AnnotationUtils.findAnnotation(((Class) targetClassInterface), DataSource.class);
        return dataSource;
    }
}

 

posted on 2021-12-07 11:16  飞哥的海  阅读(544)  评论(0)    收藏  举报