zoukankan      html  css  js  c++  java
  • 第九章 springboot + mybatis + 多数据源 (AOP实现)(转载)

    本编博客转发自:http://www.cnblogs.com/java-zhao/p/5415896.html

    1、ShopDao

    package com.xxx.firstboot.dao;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    
    import com.xxx.firstboot.domain.Shop;
    import com.xxx.firstboot.mapper.ShopMapper;
    
    @Repository
    public class ShopDao {
        @Autowired
        private ShopMapper mapper;
    
        /**
         * 获取shop
         */
        public Shop getShop(int id) {
            return mapper.getShop(id);
        }
    }
    View Code

    说明:只是去掉了设置数据源key的那一句代码

    2、DataSourceAspect

    package com.xxx.firstboot.common.datasource;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    import com.xxx.firstboot.dao.ShopDao;
    
    @Aspect
    @Component
    public class DataSourceAspect {
    
        /**
         * 使用空方法定义切点表达式
         */
        @Pointcut("execution(* com.xxx.firstboot.dao.*.*(..))")
        public void declareJointPointExpression() {
        }
    
        /**
         * 使用定义切点表达式的方法进行切点表达式的引入
         */
        @Before("declareJointPointExpression()")
        public void setDataSourceKey(JoinPoint point) {
            // 连接点所属的类实例是ShopDao
            if (point.getTarget() instanceof ShopDao) {
                DatabaseContextHolder.setDatabaseType(DatabaseType.mytestdb2);
            } else {// 连接点所属的类实例是UserDao(当然,这一步也可以不写,因为defaultTargertDataSource就是该类所用的mytestdb)
                DatabaseContextHolder.setDatabaseType(DatabaseType.mytestdb);
            }
        }
    
    }
    View Code

    注意:该切点表达式也可以用在其他切面类中,引入的时候使用"全类名.切点方法名()",例:@Before("com.xxx.firstboot.common.datasource.DataSourceAspect.declareJointPointExpression()")

  • 相关阅读:
    Java中的经典算法之冒泡排序(Bubble Sort)
    Appium环境搭建(Windows版)
    Jenkins安装与配置
    Jenkins+ANT+Jmeter 接口测试的实践(转载)
    bugku_web_phpcms1(未完待续)
    bugku_web_Bugku-cms1(未完待续)
    牛客网 PAT 算法历年真题 1010 : 月饼 (25)
    【测试的艺术】+ 封装
    【数据库】+ powerdesigner
    【Git】+IDEA中无法使用git命令
  • 原文地址:https://www.cnblogs.com/jian-xiao/p/6052527.html
Copyright © 2011-2022 走看看