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. jQuery---版本问题

    jQuery的版本 官网下载地址:http://jquery.com/download/ jQuery版本有很多,分为1.x 2.x 3.x 大版本分类: 1.x版本:能够兼容IE678浏览器 2.x ...

  2. JUC-JUC是什么?

    一.JUC是什么? java.util.concurrent在并发编程中使用的工具类 进程/线程回顾 1.进程/线程是什么? 进程:进程是一个具有一定独立功能的程序关于某个数据集合的一次运行活动.它是 ...

  3. 爬取杭电oj所有题目

    杭电oj并没有反爬 所以直接爬就好了 直接贴源码(参数可改,循环次数可改,存储路径可改) import requests from bs4 import BeautifulSoup import ti ...

  4. (转)KMP算法

    转自:http://blog.csdn.net/yutianzuijin/article/details/11954939 我们首先用一个图来描述kmp算法的思想.在字符串O中寻找f,当匹配到位置i时 ...

  5. SSM项目中的.tld文件是什么,有什么作用?怎么自定义tld文件

    原文链接:https://www.cnblogs.com/guaishoubiubiu/p/8721277.html TLD术语解释:标签库描述文件,如要在JSP页面中使用自定义JSP标签,必须首先定 ...

  6. thinkphp中简单的控制器使用

    1.在路由(route.php)中定义一条路由 Route::rule('new/:name/:id','index/News/read'); 2.在index下的controller控制器中新建一个 ...

  7. Maven设置阿里云镜像

    <mirrors> <mirror> <id>alimaven</id> <name>aliyun maven</name> & ...

  8. spring boot 2 集成JWT实现api接口认证

    JSON Web Token(JWT)是目前流行的跨域身份验证解决方案.官网:https://jwt.io/本文使用spring boot 2 集成JWT实现api接口验证. 一.JWT的数据结构 J ...

  9. 1.rest之@Get和@Post请求的区别:

    区别: (1)@Get 一般用于查询或获取资源信息, @Post一般是用于更新资源信息. (2)Url不同, @Get 请求的url: http://localhost:8080/imeter-cms ...

  10. dfs题型二(迷宫问题)

    取自:<王道论坛计算机考研机试指南>6.5节 例 6.7 Temple of the bone(九度 OJ 1461)时间限制:1 秒 内存限制:32 兆 特殊判题:否题目描述:The d ...