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;
        }
    }
  • 相关阅读:
    DUBBO+Zookeeper在Centos7中本地搭建及小案例
    【后台测试】手把手教你jmeter压测
    Netdata 是一款 Linux 性能实时监测工具
    Spring Boot(5) 集成Hibernate 日志配置
    FSTConfiguration 高性能序列化框架FST
    java BeanUtils.copyProperties
    Transformer-view java实体 转换视图 Lists.transform
    shell 命令学习
    Immutable集合
    Lists.transform的使用
  • 原文地址:https://www.cnblogs.com/yaoshi641/p/15655115.html
Copyright © 2011-2022 走看看