SpringBoot + Druid + Mybatis 配置多数据源(AOP方式)

本文详细介绍了如何在SpringBoot项目中结合Druid实现多数据源配置,并通过AOP进行数据源切换。步骤包括:配置文件设置、Druid数据源及监控配置、创建DynamicDataSource类、注入事务管理器和SQLSessionFactory、定义自定义注解选择数据源、实现切面处理、启动类排除DataSource自动配置以及使用示例。
摘要由CSDN通过智能技术生成

1、配置文件  application-dev.yml 设置

spring:
  datasource:
    ds1:
      url: jdbc:mysql://10.126.89.86:58885/xxxx?useSSL=false
      username: xxxx
      password: xxxxx
      driver-class-name: com.mysql.jdbc.Driver
    ds2:
      url: jdbc:mysql://10.126.89.86:58885/xxx?useSSL=false
      username: xxxx
      password: xxxxxx
      driver-class-name: com.mysql.jdbc.Driver
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.data.pcv.dao.model
  config-locations: classpath:mybatis/mybatis-config.xml
  configuration:
    map-underscore-to-camel-case: true
    use-generated-keys: true

2、配置Druid 多个数据源和 Druid监控Servlet

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
 
    private static final Logger log = LoggerFactory.getLogger(DruidConfig.class);
 

 
    //数据源一
    @Bean(name = "ds1DataSource" )
    @ConfigurationProperties(prefix="spring.datasource.ds1")
    public DruidDataSource ds1DataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
    //数据源二
    @Bean(name = "ds2DataSource" )
    @ConfigurationProperties(prefix="spring.datasource.ds2")
    public DruidDataSource ds2DataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();

        return druidDataSource;
    }

    @Bean
    public ServletRegistrationBean 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值