zoukankan      html  css  js  c++  java
  • sprinboot 通过@Aspect 获取接口上的注解, 若依改造为mybatisplus,并支持多数据源

    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;
        }
    }
  • 相关阅读:
    2.1.1 Speed Limit
    2.1.2 骑自行车的最短时间
    1.3.1提高实数精度的范例
    1.2.2一个数可以有多少种用连续素数之和表示
    求二倍关系的个数 1.2.1
    求平均值
    原生JS 购物车及购物页面的cookie使用
    基于Jquery的商城商品图片的放大镜效果(非组件)
    商城商品购买数量增减的完美JS效果
    弹性布局各种坑爹兼容
  • 原文地址:https://www.cnblogs.com/yaoshi641/p/15655115.html
Copyright © 2011-2022 走看看