Search code examples
springjdbctemplate

Autowireing of Qualified Datasource not working


I have a SpringBoot 2.0.4 app, and I am using JdbcTemplates. I had it all working, when I got a requirement to do a data transfer between 2 DBs.

So I set up 2 Data Sources like this:

@Configuration 
public class OracleConfiguration {

  @Bean(name = "oracleDataSource")
  @ConfigurationProperties(prefix = "oracle.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }
}

and my DAO is like this:

@Repository
@Component
public class personDao extends JdbcDaoSupport {

static final Logger logger = LoggerFactory.getLogger(CymNetworkDao.class);

@Autowired
public void setDs(@Qualifier("oracleDataSource") DataSource dataSource) {
     setDataSource(dataSource);
}

public List<PersonBean> findAll() {
    List<PersonBean> result = getJdbcTemplate().query("SELECT * FROM PERSON", new PersonRowMapper());
    return result;
}
}

I am getting this error:

 Unsatisfied dependency expressed through field 'jdbcTemplate'; 
 nested exception is   
 org.springframework.beans.factory.NoSuchBeanDefinitionException: 
 No qualifying bean of type 'org.springframework.jdbc.core.JdbcTemplate' available: 
 expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
 {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=oracleJdbcTemplate)}

My reading of tutorials was telling me to just autowire the datasource, and the jdbcTemplate would create itself. Am I qualifying wrong or something else?


Solution

  • you should create jdbcTemplate by injecting DataSource like following example

    @Repository
    public class personDao {
    private JdbcTemplate oracleJdbcTemplate;
    @Autowired
    public void setDataSource(@Qualifier("oracleDataSource") DataSource dataSource) {
        this.oracleJdbcTemplate = new JdbcTemplate(dataSource);
    }
    

    And in error message it clearly shows it was missing JdbcTemplate bean

    @org.springframework.beans.factory.annotation.Qualifier(value=oracleJdbcTemplate)}