springboot集成双数据源(多数据源)

**

一、前言

由于本人使用的是eladmin框架,在进行集成springboot+jpa多数据源时报错导致项目无法启动,现改用以下方式进行多数据源的应用集成到eladmin框架里

1.首先在yml文件配置第一个数据源
在这里插入图片描述
2,配置第二个数据源
在这里插入图片描述
3.创建两个配置文件
在这里插入图片描述

DataSourceConfig 配置类

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 javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

/***
 * 配置主数据源
 * @return
 */
@Bean(name = "fistDS")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.fist")     ##与配置的第一个数据源名称对应
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

/****
 * 配置数据源
 * @return
 */
@Bean(name = "sqlserverDS")
@ConfigurationProperties(prefix = "spring.datasource.sqlserver")  ##与配置的第二个数据源名称对应
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

}

JdbcTemplateConfig 配置类

package me.zhengjie.modules.head.util;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class JdbcTemplateConfig {

@Bean
public JdbcTemplate jdbcTemplatefalse(@Qualifier("fistDS") DataSource dataSource){
    return new JdbcTemplate(dataSource);
}

@Bean
public JdbcTemplate jdbcTemplatesqlserver(@Qualifier("sqlserverDS") DataSource dataSource){
    return new JdbcTemplate(dataSource);
}

}

3,第三步在你需要用到的类进行引用(注意,引用的类名与JdbcTemplateConfig 配置类里的方法名相对应,即可引用到对应的数据源)
在这里插入图片描述

4,引用后就可以进行增删改查操作
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值