首页>代码>使用aop进行多数据源切换 springMVC+spring+mybatis增删改查的使用>/dynamicDataSource/src/main/java/com/core/datasource/DataSourceAspect.java
package com.core.datasource;

import java.util.Map;  
import java.util.Map.Entry;  
  
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.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;  
  
 
/** 
 * 动态切换数据源切面 
 * @ClassName: DataSourceAspect    
 
 */  

public class DataSourceAspect{   
    private String defaultDataSource;  
    private Map<String, Object> targetDataSources;  
    	
    public void doBefore(JoinPoint joinPoint) {  
        boolean isSetDataSource = false;  
        String targetName = joinPoint.getTarget().getClass().getName(); 
        System.out.println("DataSourceAspect dataSourceChange doBefore 类名:"+targetName);
        System.out.println("targetDataSources:"+JSON.toJSONString(targetDataSources));
        System.out.println("defaultDataSource:"+JSON.toJSONString(defaultDataSource));
        System.out.println("------");
        for(Entry<String, Object> entry : targetDataSources.entrySet()) {  
            if(targetName.contains(entry.getKey())){  
                String value = entry.getValue().toString();  
                System.out.println("切换选择数据源:"+value);
                DynamicDataSourceHolder.setDataSource(value);                  
                isSetDataSource = true;  
                break;  
            }  
        }  
        if(!isSetDataSource) {  
        	System.out.println("切换为默认数据源"+defaultDataSource);
        	DynamicDataSourceHolder.setDataSource(defaultDataSource);  
        }  
          
    }  
      
    public void doAfterReturning(JoinPoint joinPoint) {  
    	DynamicDataSourceHolder.clearDataSource();  
    }  
  
    public Map<String, Object> getTargetDataSources() {  
        return targetDataSources;  
    }  
  
    public void setTargetDataSources(Map<String, Object> targetDataSources) {  
        this.targetDataSources = targetDataSources;  
    }  
  
    public String getDefaultDataSource() {  
        return defaultDataSource;  
    }  
  
    public void setDefaultDataSource(String defaultDataSource) {  
        this.defaultDataSource = defaultDataSource;  
    }  
      
}  
最近下载更多
543666826  LV33 2021年11月20日
qianyexingren  LV10 2020年12月30日
jiayouyy  LV8 2020年5月24日
houliukou  LV37 2020年2月4日
shuiyizq  LV5 2019年12月27日
咲暮流年  LV4 2019年10月9日
kissnicky  LV7 2019年9月24日
ChenXingyu  LV13 2019年9月18日
13734993  LV7 2019年8月8日
wxm4252  LV12 2019年8月5日
最近浏览更多
gecongkai  LV8 2023年6月22日
shuidajiao 2023年6月18日
暂无贡献等级
weijianguo  LV7 2023年5月21日
yeyuuu  LV6 2023年5月18日
finallywang 2023年4月24日
暂无贡献等级
李亮  LV19 2023年3月6日
微信网友_6248713511227392  LV11 2022年12月5日
mikyfx  LV4 2022年11月30日
00044304  LV6 2022年8月24日
Lmfbaby  LV9 2022年5月23日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友