Skip to content

Instantly share code, notes, and snippets.

@rshindo
Created September 11, 2019 18:33
Show Gist options
  • Save rshindo/c9debe8e08bd2c2e2cc26eb549e6995d to your computer and use it in GitHub Desktop.
Save rshindo/c9debe8e08bd2c2e2cc26eb549e6995d to your computer and use it in GitHub Desktop.
Spring Batchで複数のデータソースを扱う方法
package hello;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import javax.sql.DataSource;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Bean("ApplicationDataSource")
@ConfigurationProperties(prefix = "spring.datasource1")
DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
// Job Repository用のDataSourceをPrimaryにする必要あり
@Bean("JobRepositoryDataSource")
@ConfigurationProperties(prefix = "spring.datasource2")
@Primary
DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
@Bean
DefaultBatchConfigurer batchConfigurer() {
return new DefaultBatchConfigurer(dataSource2());
}
// 必要に応じてORM等の設定を行う
@Bean("ApplicationJdbcTemplate")
JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource1());
}
}
# Hikari CPの場合、urlのかわりにjdbc-urlを使う
spring:
datasource1:
jdbc-url: jdbc:postgresql://localhost:5432/postgres
username: postgres
password: pass
driver-class-name: org.postgresql.Driver
datasource2:
jdbc-url: jdbc:hsqldb:mem:test
username: sa
password:
driver-class-name: org.hsqldb.jdbc.JDBCDriver
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment