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;
        }
    }
  • 相关阅读:
    决战72hours
    学习中的十七条建议
    数学建模终结篇
    数学建模(7)建模开始
    ASP升级程序
    为blog挑选logo
    Mysql源代码分析系列(4): 主要调用流程(续)转载
    AS学习步骤
    什么是敏捷软件测试[转]
    Mysql源代码分析(6): Plugin架构介绍(续)转载
  • 原文地址:https://www.cnblogs.com/yaoshi641/p/15655115.html
Copyright © 2011-2022 走看看