springboot 集成 mybaits 多数据源

2024-03-11 03:48

本文主要是介绍springboot 集成 mybaits 多数据源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

application.yml中数据源配置:

#数据库连接  天气数据
spring:  
    datasource:   
            keshangjdbc: 
                   url: jdbc:oracle:thin:@//IP:1565/ods
                   username: 
                   password: 
                 #  driver-class-name: oracle.jdbc.driver.OracleDriver  
#数据库连接 客商数据 
            weatherjdbc: 
                  url: jdbc:oracle:thin:@//IP:1565/ods
                  username: 
                  password: 
                #  driver-class-name: oracle.jdbc.driver.OracleDriver     

对每中链接写一个配置类,主要是通过aop的方式链接注入到SqlSessionTemplate中,

客商的配置类如下:

package com.neusoft.interf.dataSources;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @author 
 * @Time:2018年12月19日 上午11:08:35
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = "com.neusoft.interf.mapper.keShang", sqlSessionTemplateRef  = "keShangSqlSessionTemplate")   //代表扫描的dao层接口,在dao层接口处理前注入数据库连接
public class keShangDataSource {
     @Bean(name = "keShangData")
        @ConfigurationProperties(prefix = "spring.datasource.keshangjdbc") // application.properteis中对应属性的前缀  

//这里特别注意的是application.properteis中对应属性一定要和DruidDataSource的属性字段一直
        @Primary
        public DataSource keShangData() {
        return new  DruidDataSource();
        }

        @Bean(name = "keShangSqlSessionFactory")
        @Primary
        public SqlSessionFactory keShangSqlSessionFactory(@Qualifier("keShangData") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);

//工程上默认使用的是Mybatis的DefaultVFS进行扫描,但是在springboot的环境下,Mybatis的DefaultVFS这个扫包会出现问

//题,所以只能修改VFS,为了清晰可见,

           VFS.addImplClass(SpringBootVFS.class);//手动触发扫描
            bean.setTypeAliasesPackage("com.neusoft.interf.entity");//对应的实体类文件夹
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/keShang/*.xml"));//对应的xml文件夹
            return bean.getObject();
        }

        @Bean(name = "keShangTransactionManager")
        @Primary
        public DataSourceTransactionManager keShangTransactionManager(@Qualifier("keShangData") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean(name = "keShangSqlSessionTemplate")
        @Primary
        public SqlSessionTemplate keShangSqlSessionTemplate(@Qualifier("keShangSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }


}
天气的配置类如下:

 

package com.neusoft.interf.dataSources;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * @author 
 * @Time:2018年12月19日 上午11:08:35
 * @version 1.0
 */
@Configuration
@MapperScan(basePackages = "com.neusoft.interf.mapper.weather", sqlSessionTemplateRef  = "weatherSqlSessionTemplate")
public class weatherDataSource {
     @Bean(name = "weatherData")
        @ConfigurationProperties(prefix = "spring.datasource.weatherjdbc") // application.properteis中对应属性的前缀
        public DataSource weatherData() {
         return new  DruidDataSource();
          //  return DataSourceBuilder.create().build();
        }

        @Bean(name = "weatherSqlSessionFactory")
        public SqlSessionFactory weatherSqlSessionFactory(@Qualifier("weatherData") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);

//工程上默认使用的是Mybatis的DefaultVFS进行扫描,但是在springboot的环境下,Mybatis的DefaultVFS这个扫包会出现问

//题,所以只能修改VFS,为了清晰可见,

           VFS.addImplClass(SpringBootVFS.class);//手动触发扫描

            bean.setTypeAliasesPackage("com.neusoft.interf.entity");
            bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/weather/*.xml"));
            return bean.getObject();
        }

        @Bean(name = "weatherTransactionManager")
        public DataSourceTransactionManager weatherTransactionManager(@Qualifier("weatherData") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean(name = "weatherSqlSessionTemplate")
        public SqlSessionTemplate weatherSqlSessionTemplate(@Qualifier("weatherSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }


}
如果有多个数据源,配置类中的@Primary只能写在其中一个,否则会报错。

 

此处有一个 技巧:

静态工具类中如果调用,springboot中bean,通过@Autowired引入bean,@PostConstruct注解方法中,把此bean

赋给静态变量

@Autowired
    private DictService dictService;
    @Autowired
    private static DictService dictService1;

    @PostConstruct
    public void init() {
        dictService1 = dictService;
    }

    public static List<Dict> getDictList(String type) {

        Map<String, Object> dictMap = Maps.newHashMap();
        List<Dict> dicts = null;
        try {

            dicts = dictService1.findAllList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Dict dict : dicts) {
            List<Dict> dictList = (List<Dict>) dictMap.get(dict.getType());
            if (dictList != null) {
                dictList.add(dict);
            } else {
                dictMap.put(dict.getType(), Lists.newArrayList(dict));
            }
        }
        List<Dict> dictList = (List<Dict>) dictMap.get(type);
        if (dictList == null) {
            dictList = Lists.newArrayList();
        }
        return dictList;
    }

}

1.@PostConstruct说明

     被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。

2.@PreDestroy说明

     被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。(详见下面的程序实践)

这篇关于springboot 集成 mybaits 多数据源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/796525

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件