Spring dynamic provisioning of multiple data sources

Source: Internet
Author: User

Requirements : project development with the Sping JdbcTemplate, before the data source only one, now the data source needs to be changed according to requirements, that is to say

A user------> need access to a database server

B user------> need access to B database server

After querying the data, we find that spring provides an abstract class Abstractroutingdatasource, which is very convenient for us to solve this problem.

Realize:

Spring configuration file Applicationcontext.xml (contains code for the related bean Class)

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:context= "Http://www.springframework.org/schema/context"Xmlns:jaxws= "Http://cxf.apache.org/jaxws"Xmlns:jaxrs= "Http://cxf.apache.org/jaxrs"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"Xmlns:tx= "Http://www.springframework.org/schema/tx"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-3.0.xsd Http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.or G/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://www.springframework.org/schema/tx http://www.spring Framework.org/schema/tx/spring-tx.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/ Schema/aop/spring-aop.xsd "><!--<bean id= "Propertyconfigurer" class= "            Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "> <property name=" Locations "> <list> <value>/WEB-INF/jdbc_config.properties</value> &L t;/list> </property> </bean> -         <!--This is the original wording <bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > < ;p roperty name= "Driverclassname" value= "${jdbc.driverclassname}"/> <property name= "url" value= "${jdbc.url}"/&      Gt <property name= "username" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password}"/&    Gt </bean> -            <BeanID= "ServerA"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource">      < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver"/>      < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/test2?useunicode=true&amp;characterencoding=utf8" />      < Propertyname= "username"value= "root"/>      < Propertyname= "Password"value= "Tiger"/>    </Bean>        <BeanID= "ServerB"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource">      < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver"/>      < Propertyname= "url"value= "Jdbc:mysql://112.112.11.132:3306/test?useunicode=true&amp;characterencoding=utf8"/>      < Propertyname= "username"value= "root" />      < Propertyname= "Password"value= "Tiger"/>    </Bean>        <!--Here's the point . -    <BeanID= "DataSource"class= "Com.rr.datasource.DynamicDataSource">    < Propertyname= "Targetdatasources">        <MapKey-type= "Java.lang.String">            <entryKey= "server127"Value-ref= "ServerA" />            <entryKey= "server112"Value-ref= "ServerB" />        </Map>    </ Property>    < Propertyname= "Defaulttargetdatasource"ref= "ServerA" /></Bean>        <!--Inject Spring JdbcTemplate -   <BeanID= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate">           < Propertyname= "DataSource"ref= "DataSource"/>   </Bean>        <!--DAO -    <BeanID= "Initdaoimpl"class= "Com.rr.dao.impl.InitDao">        < Propertyname= "JdbcTemplate"ref= "JdbcTemplate"></ Property>    </Bean>        <!--Service -    <BeanID= "Grantforcompany"class= "Com.rr.service.GrantForCompany">        < Propertyname= "Initdao"ref= "Initdaoimpl"></ Property>        < Propertyname= "JdbcTemplate"ref= "JdbcTemplate"></ Property>    </Bean>        <!--Transaction Management -   <BeanID= "Transctionmanager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager">        < Propertyname= "DataSource"ref= "DataSource"></ Property>    </Bean>    <Tx:annotation-drivenTransaction-manager= "Transctionmanager"/>         </Beans>

2: Write a Dynamicdatasource class to inherit Abstractroutingdatasource, and implement the Determinecurrentlookupkey method

Import Org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  Public class extends Abstractroutingdatasource {    @Override    protected  Object Determinecurrentlookupkey ()    {                return  databasecontextholder.getcustomertype ();      }}

3. Write a thread-safe threadlocal (this threadlocal detailed in the next blog, I have not contacted before)

 Public classdatabasecontextholder{Private Static FinalThreadlocal<string> Contextholder =NewThreadlocal<string>();  Public Static voidSetcustomertype (String customertype) {contextholder.set (customertype); }         Public StaticString Getcustomertype () {returnContextholder.get (); }         Public Static voidClearcustomertype () {contextholder.remove (); }}

4. Call a line of code when you need to switch the data source (or you can automatically switch with AOP, depending on your needs)

Targetdatasources is a map that can look at the source code provided by spring.

Reference blog:

Http://blog.sina.com.cn/s/blog_496782b1010100u1.html detailed explanation, the great God of the article

http://blog.163.com/wang_hj138%40126/blog/static/140800106201263151242338/

Spring dynamic provisioning of multiple data sources

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.