介绍
今天就跟大家聊聊有关如何春天在引导中利用mybatis实现多数据源切换,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
<强> 1。首先定义一个注解类强>
@Retention (RetentionPolicy.RUNTIME) @Target (ElementType.METHOD) 公共@ interface TargetDataSource { 字符串值();//此处接收的是数据源的名称 }
包com.example.demo.datasource; 进口com.alibaba.druid.pool.DruidDataSource; 进口com.alibaba.druid.support.http.StatViewServlet; 进口com.alibaba.druid.support.http.WebStatFilter; 进口com.example.demo.datasource.DynamicDataSource; 进口com.zaxxer.hikari.HikariConfig; 进口com.zaxxer.hikari.HikariDataSource; 进口lombok.extern.slf4j.Slf4j; 进口org.mybatis.spring.annotation.MapperScan; 进口org.springframework.beans.factory.annotation.Autowired; 进口org.springframework.beans.factory.annotation.Qualifier; 进口org.springframework.beans.factory.annotation.Value; 进口org.springframework.boot.web.servlet.FilterRegistrationBean; 进口org.springframework.boot.web.servlet.ServletRegistrationBean; 进口org.springframework.context.annotation.Bean; 进口org.springframework.context.annotation.Configuration; 进口org.springframework.jdbc.datasource.DataSourceTransactionManager; 进口org.springframework.scheduling.annotation.EnableScheduling; 进口org.springframework.scheduling.annotation.Scheduled; 进口org.springframework.transaction.PlatformTransactionManager; 进口org.w3c.dom.NodeList; 进口org.w3c.dom.Document; 进口org.w3c.dom.Element; 进口org.w3c.dom.Node; 进口javax.servlet.annotation.WebInitParam; 进口javax.servlet.annotation.WebServlet; 进口javax.sql.DataSource; 进口javax.xml.parsers.DocumentBuilder; 进口javax.xml.parsers.DocumentBuilderFactory; 进口java.lang.reflect.Field; 进口java.lang.reflect.Method; 进口java.util.HashMap; 进口java.util.Map; 进口java.io.File; 进口com.alibaba.druid.support.http.StatViewServlet;/* * *作者:wangchao *版本: *日期:2017/9/11 *描述:数据源配置 *修改历史: *日期版本作者描述 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *为什么,修改: */@ configuration @EnableScheduling 公开课DataSourceConfig {/* @ autowired 私人DBProperties属性;*/@ value (“$ {datasource.filePath}“) 私人字符串filePath;//数据源配置 @ bean (name=癲ataSource") 公共数据源的数据源(){//按照目标数据源名称和目标数据源对象的映射存放在地图中 Object> Map<对象;,targetDataSources=new HashMap<的在();//查找xml数据连接字符串 targetDataSources=getdataMap (filePath);//动态获取DBProperties类申明的属性/*字段=[]字段properties.getClass () .getDeclaredFields (); for (int i=0; igetdataMap(字符串fiePath) { 尝试{ Object> Map<对象;,targetDataSources=new HashMap<的在(); 文件xmlFile=新文件(fiePath); DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance (); DocumentBuilder builder=builderFactory.newDocumentBuilder (); 文档doc=builder.parse (xmlFile); .normalize doc.getDocumentElement () (); System.out.println(根元素:“;+ doc.getDocumentElement () .getNodeName ()); 节点列表nList=doc.getElementsByTagName (“db"); for (int i=0;i 如何春天在引导中利用mybatis实现多数据源切换