【问题标题】:Spring Boot (Batch) - Inject DatasourceSpring Boot (Batch) - 注入数据源
【发布时间】:2018-01-27 13:45:31
【问题描述】:

我有一个 Spring Boot(面向批处理)应用程序,它使用数据源来完成批处理作业并将内容写入数据库。

我在application.yml 中定义了数据源,例如:

spring:
  datasource:
    url: jdbc:h2:mem:JavaSpringBootBatch
    username: sa
    password:
  profiles: # default, development, production
    active: default, development
---
spring:
  h2:
    # ...config/settings here
  profiles: development
---
spring:
  datasource:
    # ...datasource config here
  profiles: production

问题是当我尝试将数据源注入 Spring 配置文件之一时:

@Configuration
public class PlayerBatchConfig {
  ...

  @Bean
  public ItemWriter<Player> writer(final DataSource dataSource) {
    final JdbcBatchItemWriter<Player> jdbcItemWriter = new JdbcBatchItemWriter<>();
    ...
    jdbcItemWriter.setDataSource(dataSource);
    jdbcItemWriter.setSql(sql.toString());
    return jdbcItemWriter;
  }
}

...它告诉我:

无法自动接线。 'DataSource' 类型的 bean 不止一个。

豆类: 数据源(DataSourceConfiguration.class) 数据源(EmbeddedDataSourceConfiguration.class)

我也尝试像这样注入数据源:

@Configuration
public class PlayerBatchConfig {
  @Bean
  @ConfigurationProperties(prefix = "datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  ...
}

...但没有运气 :( ,虽然这两个数据源的问题最终会消失。

任何线索如何“规避”它?

【问题讨论】:

  • 我认为 "spring.h2.console.enabled=true" 和 "spring.h2.console.path=/h2-console" 启用了 h2 数据库,并且您再次明确定义了另一个数据源,两者都是用于“开发”配置文件。因此容器被视为多个数据源。
  • 不仅仅是那些,而是default 配置文件块上的实际定义。这只让你在浏览http://.../h2-console使用development时访问H2控制台

标签: spring-boot spring-batch


【解决方案1】:

您想将annotate@Primary 一起使用的DataSource,请参阅spring-boot 文档here 以获取更多信息。除了@Primary,您可能还需要使用@Qualifier 来控制bean 注入。

【讨论】:

  • 就像我说的,问题是我不想返回并在 Java 配置中配置数据源;我想将它们保存在 YAML 文件中。无论如何,我现在就这样,因为到目前为止我找不到让它工作的方法,但是是的,如果我用 Java 配置来做这件事有点容易......
【解决方案2】:

由于您有 2 个数据源,因此您需要使用 @Qualifier 对数据源 bean 以及何时使用它们进行注释。 Spring 告诉你它不知道你想使用哪一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2016-01-28
    • 2019-10-05
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多