spring 配置多数据源

来源:互联网 发布:淘宝上的电子烟可靠吗 编辑:程序博客网 时间:2024/06/05 10:28

spring配置文件配置,添加数据源相关配置

<!-- 读写数据源 --><bean id="dataSource1" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"><property name="driverClass" value="${hibernate.driverClassName}" /><property name="jdbcUrl" value="${hibernate.url}" /><property name="username" value="${hibernate.oraclename}" /><property name="password" value="${hibernate.password}" /></bean><!-- 只读数据源 --><bean id="dataSource2" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"><property name="driverClass" value="${hibernate.driverClassName}" /><property name="jdbcUrl" value="${hibernate.url2}" /><property name="username" value="${hibernate.oraclename2}" /><property name="password" value="${hibernate.password2}" /></bean><bean id="dataSource" class="com.chinarb.group.DataSource.DynamicDataSource"><property name="targetDataSources"><map key-type="java.lang.String"><entry key="dataSource1" value-ref="dataSource1" /><entry key="dataSource2" value-ref="dataSource2" /></map></property><property name="defaultTargetDataSource" ref="dataSource1" /></bean><bean id="dataSourceInterceptor" class="com.chinarb.group.DataSource.DataSourceInterceptor" /><aop:config proxy-target-class="true" ><aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor" order="0"><!-- <aop:pointcut id="ds2" expression="execution(* com.chinarb.group.service.*.*Query*(..)) or execution(* com.chinarb.group.service.*.*query*(..)) or execution(* com.chinarb.group.service.*.*sum*(..))"/> --><aop:pointcut id="ds2" expression="execution(* com.chinarb.group.controller.*.*list*(..))"/><aop:before method="setdataSource2" pointcut-ref="ds2"/><aop:after method="cleardataSource" pointcut-ref="ds2"/></aop:aspect></aop:config>

DynamicDataSource:重写determineCurrentLookupKey()方法
public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DatabaseContextHolder.getCustomerType();}}

DataSourceInterceptor
public class DataSourceInterceptor {public void setdataSource1(JoinPoint jp) {DatabaseContextHolder.setCustomerType("dataSource1");}public void setdataSource2(JoinPoint jp) {DatabaseContextHolder.setCustomerType("dataSource2");}public void cleardataSource(JoinPoint jp) {DatabaseContextHolder.clearCustomerType();}}



DatabaseContextHolder

public class DatabaseContextHolder {private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();public static void setCustomerType(String customerType) {contextHolder.set(customerType);}public static String getCustomerType() {return contextHolder.get();}public static void clearCustomerType() {contextHolder.remove();}}

如果aop切入不到controller层,springmvc的配置文件还需要配置

<aop:aspectj-autoproxy proxy-target-class="true">  
   </aop:aspectj-autoproxy>  


原创粉丝点击