The project needs to obtain data from other websites because it is a temporary requirement. I didn’t expect that multiple data sources are needed when starting the project.
So Baidu found that it only needs to change Spring's applicationContext.xml file and write three tool classes to perfectly implement it.
applicationContext.xml
<!-- Multi-data source configuration--> <bean id="ds1"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="" /> </bean> <bean id="ds2"> <property name="driverClassName" value="" /> <property name="url" value="" /> <property name="username" value="" /> <property name="password" value="" /> </bean> <!-- Dynamic configuration of data source --> <bean id="dataSource">//This is the path to DynamicDataSource.java in your project<property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="ds_admin" key="ds1"></entry> <entry value-ref="ds_partner" key="ds2"></entry> </map> </property> <!-- Data source using ds1 by default-> <property name="defaultTargetDataSource" ref="ds_admin"></property> </bean>DataSourceContextHolder.java
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 ((String) contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); }} DataSourceType.java (set static variables)
public class DataSourceType { // Default database public static final String SOURCE_ADMIN = "ds1"; // The second database, id in applicationContext.xml public static final String SOURCE_PARTNER = "ds2";}Next is the key DynamicDataSource.java It inherits the abstract method determinedCurrentLookupKey in AbstractRoutingDataSource, which is the core of implementing the route of the data source. This method is override.
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDbType(); }}The above is an analysis of the use examples of Spring MVC Mybatis multi-data source introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!