【问题标题】:Spring batch – using two data source in one stepSpring Batch——一步使用两个数据源
【发布时间】:2021-02-25 15:10:49
【问题描述】:

目前我的 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?

如何添加另一个数据源?

谢谢

【问题讨论】:

    标签: spring spring-boot spring-batch


    【解决方案1】:

    您需要将数据源 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 
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 1970-01-01
      • 2015-08-12
      • 2013-12-18
      • 2020-11-03
      • 1970-01-01
      • 2020-12-06
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多