spring - 设置 bean 属性 'dataSource' 时出现错误无法解析对 bean 'dataSource' 的引用

标签 spring spring-boot spring-batch

我正在尝试运行基本的 SpringBatch 应用程序。我有如下的 job 配置

 @Bean
    public Step myStep(@Value("1") int chunkSize,
                                   ItemReader<Input> myReader,
                                   ItemProcessor<Input, Output> myProcessor,
                                   ItemWriter<Output> myWriter,
                                   SkipPolicy mySkipPolicy,
                                   JobRepository jobRepository,
                                   StepExecutionListener myListener) {

        return new StepBuilder("myStep", jobRepository).<Input, Output>chunk(chunkSize)
            .reader(myReader).processor(myProcessor)
            .writer(myWriter).faultTolerant()
            .skipPolicy(mySkipPolicy)
            .listener(myListener)
            .build();
    }

我在内存中使用 h2db作为数据源。这是我的数据源配置

 @Bean(name = "userDataSource")
    @ConfigurationProperties("spring.user.datasource)
    public DataSource userDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "batchDataSource")
    @ConfigurationProperties("spring.batch.datasource")
    @Primary
    public DataSource batchDataSource() {

        return DataSourceBuilder.create().build();
    }

这是我的 yaml 配置


spring:
  application:
    name: my-application
  batch:
    datasource:
      jdbcUrl: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
      max-lifetime: ${BATCH_DATASOURCE_MAX_LIFETIME:30000}
      password: sa
      username: sa
  user:
    datasource:
      jdbcUrl: jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
      max-lifetime: ${USER_DATASOURCE_MAX_LIFETIME:30000}
      password: sa
      username: sa

每当我尝试运行测试用例时,我都会遇到以下错误

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository': Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'

包含 main 方法的类位于包 example.application 中,我上面提到的所有配置类都位于包 example.application.config。我不认为这是组件扫描问题。我哪里错了?如果需要任何进一步的详细信息,请告诉我。

最佳答案

假设您使用的是 Spring Batch 5.x,我相信 jobRepository bean 正在寻找名为“dataSource”的 bean。只需将第二个 Bean 从 @Bean(name = "batchDataSource") 重命名为 @Bean(name = "dataSource")

关于spring - 设置 bean 属性 'dataSource' 时出现错误无法解析对 bean 'dataSource' 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76155811/

相关文章:

java - Bluemix Maven Spring Boot 构建和部署无效的目标版本

java - 更新单向多对一连接列值

java - 将 ShardedJedis 与 RedisTemplate 一起使用

java - 身份验证成功后,spring security HttpSession 为 null

java - 在 Java 属性文件中添加 html 字符串

java - 多对多映射 JsonMappingException : Infinite recursion (StackOverflowError)

java - 联系人无法转换为 org.springframework.core.io.support.ResourceRegion

spring-batch - pageSize 和 commit-interval 之间的 Spring Batch 差异

java - 具有固定顺序的Spring Batch多线程作业

java - 测量 Spring 批步骤执行时间