数据库状况:A数据库(oracle)+B数据库(Mysql)java
1、applicationContext.xml配置
spring
<!-- A库 --> <bean id="dataSourceA" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> ………… </bean> <!-- B库 --> <bean id="dataSourceB" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> ………… </bean> <!-- 动态数据源 --> <bean id="dynamicDataSource" class="edu.portal.demo.dataSource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="dbA" value-ref="dataSourceA" /> <entry key="dbB" value-ref="dataSourceB" /> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceA" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="true" autowire="default"> <property name="dataSource"> <ref bean="dynamicDataSource" /> </property> </bean>
2、建立DynamicDataSource并继承AbstractRoutingDataSourcesql
public class DynamicDataSource extends AbstractRoutingDataSource{ private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static final String DB_A="dbA";//该字符串与XML配置中的 public static final String DB_B="dbB"; /* (non-Javadoc) * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() */ @Override protected Object determineCurrentLookupKey() { return contextHolder.getCustomerType(); } public static void setCustomerType(String customerType) { contextHolder.set(customerType); } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); } }
3、建立目标数据源AOP,这里切点就只是针对dbAServiceBean全部方法,本质就是在dbAServiceBean的方法执行前进行数据源切换。须要要使用另一个库,就再加一个就OK了。数据库
@Service @Aspect public class AspectDbADataSource { //这里就是拦截条件,只要使用这edu.portal.demo.dbAServiceBean这个类,就会切换到dbA public static final String POINTCUT = "execution(* edu.portal.demo.dbAServiceBean.*(..))"; @Before(POINTCUT) //在edu.portal.demo.dbAServiceBean方法执行以前切换 public void changeDataSource() { DynamicDataSource.setCustomerType(DynamicDataSource.DB_A); } }
4、实现dbAServiceBean对数据库的操做。oracle
@Service public class dbAServiceBean{ @Autowired private JdbcTemplate jdbcTemplate; public void demo(){} }
通过以上配置,把使用dbA数据库的方法写在一块儿,使用dbB数据库的(这里不举例)方法写在一块儿。app
这样就能够不用管当前用的是什么库,只要在对应的ServiceBean里操做就会自动切换到对应的库,这方便。ide
因为缺少对Spring总体的学习,都是临时抱佛脚,如下几篇文章对个人帮助很多:学习
http://my.oschina.net/004/blog/367566spa