首页 > 解决方案 > Spring Batch——一步使用两个数据源

问题描述

目前,我的 spring-batch-app 配置为仅使用一个数据源(属性文件)。运行应用程序时,spring 将选择默认配置。

spring.datasource.url=jdbc:sqlserver ... 
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.naming.physical- 
strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

我的任务是创建一个需要来自另一个数据库的一些数据的作业。基本上,该步骤将从一个数据源检索数据并将数据写入另一个数据源。

对于新数据源,我创建了一个 bean:

@Bean
public DataSource melDataSource() {
    DriverManagerDataSource melDataSource = new DriverManagerDataSource();
    melDataSource.setDriverClassName("prestosql....");
    melDataSource.setUrl("....");
    melDataSource.setUsername("....");
    melDataSource.setPassword("....");
    return melDataSource;
}

这就是我调用数据源的方式:

@Autowired
private DataSource dataSource;
@Autowired
private DataSource melDataSource;

运行程序时出现以下错误:

Error creating bean with name 
'org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration': Unsatisfied 
dependency expressed through field 'dataSource'; nested exception is 
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 
'melDataSource': Requested bean is currently in creation: Is there an unresolvable circular 
 reference?

如何添加另一个数据源?

谢谢

标签: springspring-bootspring-batch

解决方案


您需要将数据源 bean 声明移动到单独的类中,并将该类导入批处理配置类中。就像是:

class DataSourceConfiguration {

   @Bean
   public DataSource melDataSource() {
      DriverManagerDataSource melDataSource = new DriverManagerDataSource();
      melDataSource.setDriverClassName("prestosql....");
      melDataSource.setUrl("....");
      melDataSource.setUsername("....");
      melDataSource.setPassword("....");
      return melDataSource;
   }
}


@Configuration
@Import(DataSourceConfiguration.class)
class BatchConfiguration {

   // use datasource bean here 
}

推荐阅读