Usage instance resolution of Spring MVC Mybatis multiple data sources
- 2020-05-17 05:40:10
- OfStack
The project needs to obtain data from other websites, because it is a temporary requirement, I did not expect to need multiple data sources when I started the project
So baidu 1, found that only need to change 1 Spring applicationContext.xml file and write three tool classes can be perfectly realized
applicationContext.xml
<!-- Multi-data source configuration -->
<bean id="ds1" class="org.apache.commons.dbcp.BasicDataSource">
<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" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="" />
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<!-- Dynamic configuration data source -->
<bean id="dataSource" class="com.test.utils.DynamicDataSource">// This is your project DynamicDataSource.java The path of the
<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>
<!-- Use the default ds1 The data source -->
<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 variable)
public class DataSourceType {
// Default database
public static final String SOURCE_ADMIN = "ds1";
// The first 2 Database, in applicationContext.xml In the id
public static final String SOURCE_PARTNER = "ds2";
}
Next is the key: DynamicDataSource.java, which inherits the abstract method determineCurrentLookupKey from AbstractRoutingDataSource, which is the core of route implementing the data source.
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDbType();
}
}