侧边栏壁纸
博主头像
流殃博主等级

用微笑面对生活

  • 累计撰写 176 篇文章
  • 累计创建 43 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

多数据源配置

流殃
2022-11-08 / 0 评论 / 0 点赞 / 217 阅读 / 314 字 / 正在检测是否收录...

依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.23</version>
</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

实现

package com.example.test;

import javax.sql.DataSource;
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.jdbc.core.JdbcTemplate;

@Configuration
public class DataSourceConfig {
  @Bean("dataSource")
  @Qualifier("dataSource")
  @Primary
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

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

  @Bean("ebadataSource")
  @Qualifier("ebadataSource")
  @ConfigurationProperties(prefix = "spring.datasource.eba")
  public DataSource EbaDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean("jdbcTemplate")
  public JdbcTemplate EbajdbcTemplate(@Qualifier("ebadataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }

  @Bean("ucmdataSource")
  @Qualifier("ucmdataSource")
  @ConfigurationProperties(prefix = "spring.datasource.ucm")
  public DataSource UcmDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean("jdbcTemplate")
  public JdbcTemplate UcmJdbcTemplate(@Qualifier("ucmdataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }
}

配置文件

# 主数据库配置
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=
# eba数据库配置
spring.datasource.eba.url=
spring.datasource.eba.username=
spring.datasource.eba.password=
spring.datasource.eba.driver-class-name=
# ucm数据库配置
spring.datasource.ucm.url=
spring.datasource.ucm.username=
spring.datasource.ucm.password=
spring.datasource.ucm.driver-class-name=
0

评论区