【问题标题】:Configuring DataSource and JdbcTemplate in a Standalone Spring Boot Application在独立 Spring Boot 应用程序中配置 DataSource 和 JdbcTemplate
【发布时间】:2018-08-18 05:22:14
【问题描述】:

我正在编写一个独立的 Spring Boot 应用程序,它将从 SQLServer 获取数据并插入 MySQL 数据库。

我认为我正确地构建了应用程序并相信我走在正确的轨道上。但是,我无法弄清楚:

  1. 如何设置/配置 DataSource 和 JdbcTemplate。
  2. 那么如何设置两个不同的 DataSource 和 JdbcTemplate;一个用于 SQLServer,一个用于 MySQL。

Here 是我的 Git repo 链接,供您查看我的项目结构和初始代码。

有人可以帮助我了解如何设置 DataSourceJdbcTemplate

谢谢。

【问题讨论】:

  • 请先google,medium.com/@joeclever/…
  • @clevertension - 感谢您的回复!这回答了我的第二个问题。你是对的,我可以搜索它。然而,我在 SO 上创建这篇文章的主要原因是为了得到第一个问题的答案。既然我问了,我也想放第二个。如果这不是正确的方法,我很抱歉。绝对不是要浪费任何人的时间。在创建这篇文章之前,我确实做了很多搜索。我赞成您对第二个问题的回答。谢谢。

标签: spring-boot spring-data datasource spring-jdbc jdbctemplate


【解决方案1】:

我希望你知道如何在这样的属性文件中为每个 db 提供 2 组属性。

# Oracle DB - "foo"
spring.datasource.hikari.jdbcUrl=jdbc:oracle:thin:@//db-server-foo:1521/FOO
spring.datasource.hikari.username=fooadmin
spring.datasource.hikari.password=foo123
spring.datasource.hikari.driverClassName=oracle.jdbc.OracleDriver
# Ignite DB - "bar"
bar.datasource.hikari.url=jdbc:postgresql://db-server-bar:5432/bar
bar.datasource.hikari.username=baradmin
bar.datasource.hikari.password=bar123
bar.datasource.driver-class-name=org.postgresql.Driver

然后像这样配置数据源和jdbc模板。

 /**
 * Auto-configured DataSource
 */
@ConfigurationProperties(prefix = "spring.datasource.hikari")
@Bean
@Primary
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

/**
 * New Data source declared to connect to the Ignite in-memory Cache database.
 *
 * @return instance of DriverManagerDataSource
 */
@ConfigurationProperties(prefix = "bar.datasource.hikari")
@Bean
public DataSource igniteDataSource() {
    return DataSourceBuilder.create().build();
}

/**
 * Initialize the jdbc template to connect to ignite datasource.
 *
 * @return instance of JdbcTemplate to connect ot <code>igniteDataSource()</code>
 */
@Bean
@Primary
public JdbcTemplate igniteTemplate() {
    return new JdbcTemplate(igniteDataSource());
}

/**
 * Initialize the jdbc template to connect to the Oracle database.
 *
 * @return instance of JdbcTemplate to connect ot <code>dataSource()</code>
 */
@Bean
public JdbcTemplate dbjdbcTemplate() {
    return new JdbcTemplate(dataSource());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 2016-07-04
    • 2023-03-10
    • 2020-12-05
    • 2021-05-24
    • 1970-01-01
    • 2015-05-03
    • 2017-07-04
    相关资源
    最近更新 更多