SpringMVC+MyBitis+多数据源切换

来源:互联网 发布:psv淘宝 编辑:程序博客网 时间:2024/06/13 21:27
转载请注明出处:http://blog.csdn.net/l1028386804/article/details/48163279

spring mvc+mybatis+多数据源切换 选取Oracle,MySQL作为例子切换数据源。oracle为默认数据源,在测试的action中,进行mysql和oracle的动态切换。

web.xml

[html] view plain copy
  1. <context-param>  
  2.     <param-name>webAppRootKey</param-name>  
  3.     <param-value>trac</param-value>  
  4. </context-param>  
  5.   
  6. <!-- Spring的log4j监听器 -->  
  7. <listener>  
  8.     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  9. </listener>  
  10.   
  11. <!-- 字符集 过滤器 -->  
  12. <filter>  
  13.     <filter-name>CharacterEncodingFilter</filter-name>  
  14.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  15.     <init-param>  
  16.         <param-name>encoding</param-name>  
  17.         <param-value>utf8</param-value>  
  18.     </init-param>  
  19.     <init-param>  
  20.         <param-name>forceEncoding</param-name>  
  21.         <param-value>true</param-value>  
  22.     </init-param>  
  23. </filter>  
  24. <filter-mapping>  
  25.     <filter-name>CharacterEncodingFilter</filter-name>  
  26.     <url-pattern>/*</url-pattern>  
  27. </filter-mapping>  
  28.   
  29. <!-- Spring view分发器 -->  
  30. <servlet>  
  31.     <servlet-name>dispatcher</servlet-name>  
  32.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  33.     <init-param>  
  34.         <param-name>contextConfigLocation</param-name>  
  35.         <param-value>/WEB-INF/dispatcher.xml</param-value>  
  36.     </init-param>  
  37.     <load-on-startup>1</load-on-startup>  
  38. </servlet>  
  39. <servlet-mapping>  
  40.     <servlet-name>dispatcher</servlet-name>  
  41.     <url-pattern>*.action</url-pattern>  
  42. </servlet-mapping>  
  43.   
  44. <listener>  
  45.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  46. </listener>  

dispatcher.xml

[html] view plain copy
  1. <mvc:annotation-driven />  
  2. <context:component-scan base-package="com.trac" />  
  3.   
  4. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />  
  5.   
  6. <!-- freemarker config -->  
  7. <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  8.     <property name="templateLoaderPath" value="/WEB-INF/freemarker/" />  
  9.     <property name="freemarkerVariables">  
  10.         <map>  
  11.             <entry key="xml_escape" value-ref="fmXmlEscape" />  
  12.         </map>  
  13.     </property>  
  14.     <property name="freemarkerSettings">  
  15.         <props>  
  16.             <prop key="defaultEncoding">UTF-8</prop>  
  17.         </props>  
  18.     </property>  
  19. </bean>  
  20.   
  21. <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />  
  22.   
  23. <!-- View resolvers can also be configured with ResourceBundles or XML files.   
  24.     If you need different view resolving based on Locale, you have to use the   
  25.     resource bundle resolver. -->  
  26. <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
  27.     <property name="exposeRequestAttributes" value="true" />  
  28.     <property name="exposeSessionAttributes" value="true" />  
  29.     <property name="exposeSpringMacroHelpers" value="true" />  
  30.     <property name="contentType" value="text/html;charset=UTF-8" />  
  31.     <property name="cache" value="true" />  
  32.     <property name="prefix" value="" />  
  33.     <property name="suffix" value=".ftl" />  
  34. </bean>  

applicationContext.xml

[html] view plain copy
  1. <bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  2. </bean>  
  3.   
  4. <bean id="mySqlDataSource" parent="parentDataSource">  
  5.     <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>  
  6.     <property name="url" value="jdbc:mysql://localhost:3306/test"></property>  
  7.     <property name="username" value="root"></property>  
  8.     <property name="password" value="root"></property>  
  9. </bean>  
  10.   
  11. <bean id="oracleDataSource" parent="parentDataSource">  
  12.     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>  
  13.     <property name="url" value="jdbc:oracle:thin:@10.16.17.40:1531:addb"></property>  
  14.     <property name="username" value="trac"></property>  
  15.     <property name="password" value="trac"></property>  
  16. </bean>  
  17.   
  18. <bean id="dataSource" class="com.trac.dao.datasource.DataSources">  
  19.     <property name="targetDataSources">  
  20.         <map key-type="java.lang.String">  
  21.             <entry value-ref="mySqlDataSource" key="MYSQL"></entry>  
  22.             <entry value-ref="oracleDataSource" key="ORACLE"></entry>  
  23.         </map>  
  24.     </property>  
  25.     <property name="defaultTargetDataSource" ref="oracleDataSource"></property>  
  26. </bean>  
  27.   
  28. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  29.     <property name="dataSource" ref="dataSource" />  
  30. </bean>  
  31.   
  32. <!-- 创建SqlSessionFactory,同时指定数据源和mapper -->  
  33. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  34.     <property name="dataSource" ref="dataSource" />  
  35.     <property name="mapperLocations" value="classpath*:com/trac/ibatis/dbcp/*.xml" />  
  36. </bean>  
  37.   
  38. <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
  39.     <constructor-arg index="0" ref="sqlSessionFactory" />  
  40. </bean>  
  41.   
  42. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  43.     <property name="basePackage" value="com.trac.dao" />  
  44. </bean>  
配置 parentDataSource 的父bean.再配置多个数据源继承这个父bean,对driverClass,url,username,password,等数据源连接参数进行各自的重写。例如 mySqlDataSource ,在 DataSources bean中注入所有要切换的数据源,并且设置默认的数据源。

DataSourceInstances.java

[java] view plain copy
  1. /** 
  2.  * 定义数据源的标识, 和applicationContext.xml中 DataSources 的 targetDataSources 的key对应 
  3.  * @author liuyazhuang 
  4.  */  
  5. public class DataSourceInstances{  
  6.     public static final String MYSQL="MYSQL";  
  7.     public static final String ORACLE="ORACLE";  
  8. }     

DataSourceSwitch.java

[java] view plain copy
  1. /** 
  2.  * 
  3.  * @author liuyazhuang 
  4.  */  
  5. public class DataSourceSwitch{  
  6.     private static final ThreadLocal contextHolder=new ThreadLocal();  
  7.       
  8.     public static void setDataSourceType(String dataSourceType){  
  9.         contextHolder.set(dataSourceType);  
  10.     }  
  11.       
  12.     public static String getDataSourceType(){  
  13.         return (String) contextHolder.get();  
  14.     }  
  15.       
  16.     public static void clearDataSourceType(){  
  17.         contextHolder.remove();  
  18.     }  
  19. }  

DataSources.java

[java] view plain copy
  1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  2. /** 
  3.  *配置于applicationContext 中,线程局部变量ThreadLocal contextHolder 保存当前需要的数据源类型,当 DataSourceSwitch. setDataSourceType(DataSourceInstances.XXX) 保存当前需要的数据源类型的时候,DataSources 会从当前线程中查找线程变量的数据源类型,从而决定使用何种数据源 
  4.  
  5.  * @author liuyazhuang 
  6.  */  
  7. public class DataSources extends AbstractRoutingDataSource{  
  8.     @Override  
  9.     protected Object determineCurrentLookupKey() {  
  10.         return DataSourceSwitch.getDataSourceType();  
  11.     }  
  12. }  

TestAction.java

[java] view plain copy
  1. @Controller  
  2. @SuppressWarnings("unused")  
  3. public class TestAction {  
  4. @Autowired  
  5.     TestMapper testMapper;  
  6.    @RequestMapping("/test.action")  
  7.     public ModelAndView test(  
  8.             HttpServletRequest request,  
  9.             HttpServletResponse resp){  
  10.         ModelAndView model = new ModelAndView("test");  
  11.         model.addObject("test1""这是一个测试,获取默认数据连接MYSQL:"+testMapper.test());  
  12.         DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE);  
  13.         model.addObject("test2""这是一个测试,获取数据连接ORACLE:"+testMapper.test());  
  14.         DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);  
  15.         model.addObject("test3""这是一个测试,获取数据连接MYSQL:"+testMapper.test());  
  16.         return model;  
  17.     }  
  18. }  
0 0
原创粉丝点击