Spring-Boot's auto-configurer seems good for simple applications. For example it automatically creates DataSource and JdbcTemplate, when you need to connect to the database. But what about less trivial configuration, when you have several different databases?

I found the way to have multiple DataSources for Spring-Boot-based application.

In the sample below I have two special (db-related) Configurations, one properties file with connections' parameters and two Repositories.

Each @Repository connects with appropriate database through separate DataSource.

application.properties
spring.ds_items.driverClassName=org.postgresql.Driver
spring.ds_items.url=jdbc:postgresql://srv0/test
spring.ds_items.username=test0
spring.ds_items.password=test0 spring.ds_users.driverClassName=org.postgresql.Driver
spring.ds_users.url=jdbc:postgresql://srv1/test
spring.ds_users.username=test1
spring.ds_users.password=test1


DatabaseItemsConfig.java
package sb; 

import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
@ConfigurationProperties(name = "spring.ds_items")
public class DatabaseItemsConfig extends TomcatDataSourceConfiguration { @Bean(name = "dsItems")
public DataSource dataSource() {
return super.dataSource();
} @Bean(name = "jdbcItems")
public JdbcTemplate jdbcTemplate(DataSource dsItems) {
return new JdbcTemplate(dsItems);
}
}
DatabaseUsersConfig.java
package sb; 

import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
@ConfigurationProperties(name = "spring.ds_users")
public class DatabaseUsersConfig extends TomcatDataSourceConfiguration { @Bean(name = "dsUsers")
public DataSource dataSource() {
return super.dataSource();
} @Bean(name = "jdbcUsers")
public JdbcTemplate jdbcTemplate(DataSource dsUsers) {
return new JdbcTemplate(dsUsers);
} }
ItemRepository.java
package sb; 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import java.sql.ResultSet;
import java.sql.SQLException; @Repository
public class ItemRepository {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
@Qualifier("jdbcItems")
protected JdbcTemplate jdbc; public Item getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
} private static final RowMapper<Item> itemMapper = new RowMapper<Item>() {
public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
Item item = new Item(rs.getLong("id"), rs.getString("title"));
item.price = rs.getDouble("id");
return item;
}
};
}
UserRepository.java
package sb; 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import java.sql.ResultSet;
import java.sql.SQLException; @Repository
public class UserRepository {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
@Qualifier("jdbcUsers")
protected JdbcTemplate jdbc; public User getUser(long id) {
return jdbc.queryForObject("SELECT * FROM sb_user WHERE id=?", userMapper, id);
} private static final RowMapper<User> userMapper = new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(rs.getLong("id"), rs.getString("name"));
user.alias = rs.getString("alias");
return user;
}
};
}
Controller.java
package sb; 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class Controller {
protected final Logger log = LoggerFactory.getLogger(getClass()); @Autowired
private UserRepository users; @Autowired
private ItemRepository items; @RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
} @RequestMapping("user")
public User getUser(@RequestParam("id") long id) {
log.info("Get user");
return users.getUser(id);
} @RequestMapping("item")
public Item getItem(@RequestParam("id") long id) {
log.info("Get item");
return items.getItem(id);
} }
Application.java
package sb; 

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
@Configuration
@ComponentScan(basePackages = "sb")
public class Application { public static void main(String[] args) throws Throwable {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}

Spring-boot JDBC with multiple DataSources sample的更多相关文章

  1. 【Spring-boot多数据库】Spring-boot JDBC with multiple DataSources sample

    application.properties spring.ds_items.driverClassName=org.postgresql.Driver spring.ds_items.url=jdb ...

  2. (转) Spring Boot JDBC 连接数据库

    文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. 1 JDBC 连接数据库 1.1 属性配 ...

  3. Spring Boot JDBC 连接数据库

    文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. JDBC 连接数据库 1.属性配置文件( ...

  4. Spring boot + jdbc学习笔记

    pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...

  5. Spring Boot JDBC:加载DataSource过程的源码分析及yml中DataSource的配置

    装载至:https://www.cnblogs.com/storml/p/8611388.html Spring Boot实现了自动加载DataSource及相关配置.当然,使用时加上@EnableA ...

  6. Spring Boot JDBC 使用教程

    总是要用到数据库的嘛,曾经我一度以为,写代码,编程就是搞数据库增删改查,甚至你设计一个系统,大部分时候在为如何设计关系型数据库努力,究其原因,是因为关系型数据库是逻辑的主要呈现. 这个系列,主要是对 ...

  7. Spring Boot: Jdbc javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify

    jdbc:mysql://127.0.0.1:3306/xxx?useSSL=false 在后面添加?useSSL=false即可 参考网站

  8. 10. Spring Boot JDBC 连接数据库

    转自:https://blog.csdn.net/catoop/article/details/50507516

  9. 二、spring Boot构建的Web应用中,基于MySQL数据库的几种数据库连接方式进行介绍

    包括JDBC.JPA.MyBatis.多数据源和事务. 一.JDBC 连接数据库 1.属性配置文件(application.properties) spring.datasource.url=jdbc ...

随机推荐

  1. Docker+JMeter+InfluxDB+Grafana从容器内部发起压测

    1.自由定制JMeter镜像: Dockerfile文件: FROM java:8# 基础镜像 MAINTAINER yangjianliang <526861348@qq.com># 作 ...

  2. 巨杉Tech | 微服务趋势下的数据库设计与应用简析

    周五(7月12日)巨杉数据库参与了由得到App主办八里庄技术沙龙活动,分享主题是关于分布式数据库架构与实战. 以下就是根据巨杉数据库现场分享的内容进行的分享实录整理. 巨杉数据库简介 巨杉,专注新一代 ...

  3. Windows下解决github push failed (remote: Permission to userA/XXXX.git denied to userB.) 上传gitHub失败报错

    Windows环境下解决 github push failed (remote: Permission to userA/XXXX.git denied to userB.) · 初学GitHub的朋 ...

  4. 2019杭电多校第五场 discrete logarithm problem

    https://vjudge.net/contest/317493#problem/I

  5. Codeforces Round #615 (Div. 3) A-F简要题解

    contest链接:https://codeforces.com/contest/1294 A. 给出a.b.c三个数,从n中分配给a.b.c,问能否使得a = b = c.计算a,b,c三个数的差值 ...

  6. hdu1716 排列2

    12  21 123 132  213 231 321 312 .... 每次都将后面n-1位进行全排列.递归的出口当起始坐标等于终止坐标时.需要还原. 设计标记数组.因为需要从小到大输出. #def ...

  7. thinkphp 二级域名绑定模块,导致设置的路由被多域名共用的问题解决方案

    问题背景: 在router.php路由配置文件设置了二级域名和路由设置 use think\Route; Route::domain('www','index'); Route::domain('ad ...

  8. php & c# DES

    php <?php class DES { var $key; var $iv; //偏移量 function DES($key = '11001100', $iv=0 ) { //key长度8 ...

  9. 在UTF-8页面中引入编码为GBK的JavaScript文件乱码问题了

    原文地址:http://js8.in/2009/12/11/%E5%AF%B9%E5%BC%95%E7%94%A8%E5%A4%96%E9%83%A8javascript%E9%A1%B5%E9%9D ...

  10. 密码学笔记-一段base64wp

    CTF--练习平台 例题: 一段Base64 flag格式:flag{xxxxxxxxxxxxx} 附件: base64.txt 1.base64解码:http://base64.xpcha.com/ ...