简体   繁体   English

Spring Boot 找不到 JdbcTemplate 的数据源

[英]Spring Boot can't find DataSource for JdbcTemplate

I have a Spring Boot application that happens to use Camunda for BPMN.我有一个 Spring Boot 应用程序,恰好将 Camunda 用于 BPMN。 Everything works fine.一切正常。 I have the Hikairi DBPool and the datasource properties in my application.properties file.我的 application.properties 文件中有 Hikairi DBPool 和数据源属性。 Every thing runs fine, and workflows work etc...一切都运行良好,工作流程工作等......

I now want to access my DB via JdbcTemplate, using the same DataSource, as all the tables are on the same DB.我现在想通过 JdbcTemplate 访问我的数据库,使用相同的数据源,因为所有表都在同一个数据库上。 I add this class:我添加这个类:

@Component
public class MyDao extends JdbcDaoSupport {

  public MyRow getMyRowById(int id) {
    String sql = "select * from MyTable where id = ?";
    try {
        MyRow myRow = (MyRow)getJdbcTemplate().queryForObject(sql, new Object[] { id }, new MyRowMapper());
        return myRow;
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return null;
  }
}

And I get the error:我得到错误:

Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required

How is that possible when I know it's there.当我知道它在那里时,这怎么可能。 I see in the logs that Hikari is using it and adding itself as the DataSource for pooling.我在日志中看到 Hikari 正在使用它并将自己添加为用于池的数据源。 If I simply remove the @Component and it at least deploys, but as you would think, it throws a null pointer at the getJdbcTemplate() call.如果我简单地删除 @Component 并且它至少会部署,但正如您所想的那样,它会在 getJdbcTemplate() 调用中抛出一个空指针。

Is there an annotation I am missing to get this to autowire correctly and expose the DataSource to my JdbcTemplate?是否缺少注释以使其正确自动装配并将数据源公开给我的 JdbcTemplate?

First, you should annotate your MyDao with the @Repository annotation and not with just the @Component one.首先,您应该使用@Repository注释而不是仅使用@Component注释来注释您的MyDao For this reason, please take a moment to read What's the difference between @Component, @Repository & @Service annotations in Spring?为此,请花点时间阅读Spring 中 @Component、@Repository 和 @Service 注释之间的区别是什么? . .

Second, looking at your exception, seems you are missing the injection of the jdbcTemplate/datasource in the MyDao .其次,查看您的异常,似乎您错过了MyDao jdbcTemplate/datasource 的MyDao For this point, if you are working with the datasource itself and not with the JdbcTemplate , you can inject the datasource as following:对于这一点,如果您使用的是数据源本身而不是JdbcTemplate ,则可以按如下方式注入数据源:

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

However, if you are using the JdbcTemplate , you can add a setter injection inside you MyDao as following:但是,如果您使用的是JdbcTemplate ,则可以在MyDao添加一个 setter 注入,如下所示:

@Autowired
public void setJt(JdbcTemplate jdbcTemplate) {
     setJdbcTemplate(jdbcTemplate);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM