• 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;
        }
    }
  • 相关阅读:
    eclipse 10个常用 快捷键
    struts2 s:set标签
    web项目的路径问题
    linux系统中用户切换
    java的多线程(一)
    Mongodb 与 Mongoose 的使用
    escape()、encodeURI()、encodeURIComponent()区别详解
    JSON WEB TOKEN
    关于使用REST API
    mac下设置mongodb开机启动方法
  • 原文地址:https://www.cnblogs.com/yaoshi641/p/15655115.html
Copyright © 2020-2023  润新知