基于注解的形式在Spring中实现对多数据源配置和使用

     主要参考:基于注解的Spring多数据源配置和使用,在此感谢。。。

     如下结合配置做简要说明:

    1、定义一个用来指定数据源的注解,如下:

package com.ryan.core.datasource;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
	String value();
}

    2、定义一个数据库切换工具类:

package com.ryan.core.datasource;


public class DataSourceContextHolder {
	
	/**
	 * 注意:数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
	 */
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
	
	public static void setDbType(String dbType){
		contextHolder.set(dbType);
	}
	
	public static String getDbType(){
		return contextHolder.get();
	}
	
	public static void clearDbType(){
		contextHolder.remove();
	}

}


    3、实现AbstractRoutingDataSource抽象类中的determineCurrentLookupKey方法,用于切换到指定的数据源:

package com.ryan.core.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource  {

	@Override
	protected Object determineCurrentLookupKey() {
		return DataSourceContextHolder.getDbType();
	}
	
}


    4、定义AOP,增加切面拦截:

package com.ryan.core.datasource.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ryan.core.datasource.DataSource;
import com.ryan.core.datasource.DataSourceContextHolder;

public class DataSourceAspect {
	
	private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

	/**
	 * 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
	 * @param point
	 * @throws Exception
	 */
	public void intercept(JoinPoint point) throws Exception 
	{
		Class<?> target = point.getTarget().getClass();
		MethodSignature signature = (MethodSignature) point.getSignature();
		// 默认使用目标类型的注解,如果没有则使用其实现接口的注解
		for (Class<?> clazz : target.getInterfaces()) {
			resolveDataSource(clazz, signature.getMethod());
		}
		resolveDataSource(target, signature.getMethod());
	}

	/**
	 * 提取目标对象方法注解和类型注解中的数据源标识
	 * @param clazz
	 * @param method
	 */
	private void resolveDataSource(Class<?> clazz, Method method) 
	{
		try {
			Class<?>[] types = method.getParameterTypes();
			// 默认使用类型注解
			if (clazz.isAnnotationPresent(DataSource.class)) {
				DataSource source = clazz.getAnnotation(DataSource.class);
				DataSourceContextHolder.setDbType(source.value());
			}
			
			// 方法注解可以覆盖类型注解
			Method m = clazz.getMethod(method.getName(), types);
			if (m != null && m.isAnnotationPresent(DataSource.class)) {
				DataSource source = m.getAnnotation(DataSource.class);
				DataSourceContextHolder.setDbType(source.value());
			}
		} catch (Exception e) {
			logger.error("数据源切换出现异常", e);
		}
	}

}


    5、在Spring的配置文件中增加数据源配置以及AOP拦截规则:

<bean id="cmsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://192.168.1.1:3306/cmsdb" />
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
	<bean id="cvsDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://192.168.1.1:3306/cvsdb" />
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
	</bean>
	
	<!-- 动态配置数据源 -->
	<bean id="dataSource" class="com.ryan.core.datasource.DynamicDataSource">
		<property name ="targetDataSources">  
             <map key-type ="java.lang.String">  
             	<entry value-ref ="cmsDataSource" key= "cmsDataSource"></entry>  
                <entry value-ref ="cvsDataSource" key="cvsDataSource"></entry>
             </map>  
		</property>
		<!-- 默认使用cebdb的数据源 -->
		<property name ="defaultTargetDataSource" ref= "cmsDataSource"></property>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="mapperLocations" value="classpath:com/ryan/mapper/*.xml"/>
	</bean>
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ryan.mapper"/>
	</bean>

	<aop:config>
        <aop:aspect ref="dataSourceAspect">
        	<!-- 配置拦截规则,拦截所有请求方法 -->
	        <aop:pointcut id="dataSourcePointcut" expression ="execution(* com.ryan.controller..*.*(..))"/>
            <aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
        </aop:aspect>
    </aop:config>
    
    <bean id="dataSourceAspect" class="com.ryan.core.datasource.aspect.DataSourceAspect" />


    6、在Controller类或方法中增加@DataSource,示例中配置的Controller级别上,如下:

package com.ryan.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ryan.core.datasource.DataSource;
import com.ryan.mapper.UserHolder;
import com.ryan.service.UserService;

@Controller
@RequestMapping(value="/cms/user")
@DataSource("cmsDataSource")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/index")
	public ModelAndView index(HttpServletRequest req, HttpServletResponse resp){
		return new ModelAndView("/user/index");
	}
	
	@RequestMapping(value="/list", method={RequestMethod.POST}, produces="application/json;charset=UTF-8")
	@ResponseBody
	public List<UserHolder> getList(@RequestBody UserHolder holder, HttpServletRequest req, HttpServletResponse resp){
		
		List<UserHolder> userList = this.userService.getList(holder);
		
		return userList;
	}
}

 



 
 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值