數據庫狀況: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