0
votes

I have a Spring Boot (batch-oriented) application that uses a datasource in order to finalize a batch job and write stuff to the database.

I have the datasource(s) defined inside the application.yml like:

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

The issue is when I try to inject the datasource into one of the Spring config files:

@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;
  }
}

...it tells me that:

Could not autowire. There is more than one bean of 'DataSource' type.

Beans: dataSource (DataSourceConfiguration.class) dataSource (EmbeddedDataSourceConfiguration.class)

I also tried to inject the datasource like:

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

  ...
}

...but no luck :( , although the issue with the two datasources goes away eventually.

Any clues how to "circumvent" that?

2
i think "spring.h2.console.enabled=true" and "spring.h2.console.path=/h2-console" enables h2 database and you have defined another datasource explicitly again and both are for "development" profile. Thus container seeing as multiple datasource. - surya
Not quite just those, but the actual definition on the default profile chunk. That only let you access the H2 console on when development is used by browsing http://.../h2-console - x80486

2 Answers

0
votes

Since you have 2 datasources you need the annotate them with the @Qualifier the datasources bean and when you use them as well. Spring is telling you it doesn't know which one you want to use.

0
votes

The DataSource which you want to use annotate it with @Primary, refer spring-boot documentation here for further info. Along with @Primary you might also need to use @Qualifier for controlling the bean injection.