title: Spring Boot (Batch) - Inject Datasource
body: <p>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.</p>
  
  <p>I have the datasource(s) defined inside the <code>application.yml</code> like:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The issue is when I try to inject the datasource into one of the Spring config files:</p>
  
  <pre><code>@Configuration
  public class PlayerBatchConfig {
    ...
  
    @Bean
    public ItemWriter&lt;Player&gt; writer(final DataSource dataSource) {
      final JdbcBatchItemWriter&lt;Player&gt; jdbcItemWriter = new JdbcBatchItemWriter&lt;&gt;();
      ...
      jdbcItemWriter.setDataSource(dataSource);
      jdbcItemWriter.setSql(sql.toString());
      return jdbcItemWriter;
    }
  }
  </code></pre>
  
  <p>...it tells me that:</p>
  
  <blockquote>
    <p>Could not autowire. There is more than one bean of 'DataSource' type.</p>
    
    <p>Beans:
    dataSource (DataSourceConfiguration.class)
    dataSource (EmbeddedDataSourceConfiguration.class)</p>
  </blockquote>
  
  <p>I also tried to inject the datasource like:</p>
  
  <pre><code>@Configuration
  public class PlayerBatchConfig {
    @Bean
    @ConfigurationProperties(prefix = "datasource")
    public DataSource dataSource() {
      return DataSourceBuilder.create().build();
    }
  
    ...
  }
  </code></pre>
  
  <p>...but no luck :( , although the issue with the two datasources goes away eventually.</p>
  
  <p>Any clues how to "circumvent" that?</p>