Project needs to get data from other sites, because it is a temporary addition to the requirements, at the beginning of the project did not expect to need multiple data sources
So Baidu a bit, found that only need to change the spring applicationcontext.xml files and write three tool classes can be a perfect implementation
Applicationcontext.xml
<!--multiple data source configuration--> <bean id= "DS1" class= "Org.apache.commons.dbcp.BasicDataSource" > <property name= "Driver" ClassName "value=" ${jdbc.driverclassname} "/> <property name=" url "value=" ${jdbc.url} "/> <property name=" Username "value=" ${jdbc.username} "/> <property name=" password "value=" "/> </bean> <bean id=" DS2 "C lass= "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 the Dynamicdatasource.java path 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> <! --Use DS1 data source 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 variable)
public class DatasourceType {
//default database public
static final String source_admin = "DS1";
The second database, in the Applicationcontext.xml ID public
static final String Source_partner = "DS2";
}
And then this is the key Dynamicdatasource.java. It inherits the abstract method in Abstractroutingdatasource Determinecurrentlookupkey is the core of the route that implements the data source. This method is override here.
Import Org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class Dynamicdatasource extends Abstractroutingdatasource {
@Override
protected Object Determinecurrentlookupkey () {return
datasourcecontextholder.getdbtype ();
}
}
The above is a small series to introduce the spring MVC mybatis multiple data sources of the use of examples, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!