【问题标题】:Not able to connect to Oracle Database using JDBC Driver in Spring Boot无法在 Spring Boot 中使用 JDBC 驱动程序连接到 Oracle 数据库
【发布时间】:2017-10-16 10:44:39
【问题描述】:

我已经在 application.properties 文件中写入了数据库的 url、用户名等。我还在 JdbcTemplate 的控制器中定义了@Autowired 注释。但是现在当我执行时,我得到了这个错误 -

应用程序启动失败


说明:

com.sab.Controller 中的字段 jdbc 需要一个无法找到的“org.springframework.jdbc.core.JdbcTemplate”类型的 bean。 - 未加载 Bean 方法“jdbcTemplate”,因为 @ConditionalOnSingleCandidate(类型:javax.sql.DataSource;SearchStrategy:all)没有找到任何 bean

行动:

考虑重新审视上述条件或在配置中定义 org.springframework.jdbc.core.JdbcTemplate 类型的 bean。

谁能帮我解决这个错误。

【问题讨论】:

  • 发布配置并确保您拥有正确的依赖项。也看here
  • 该错误消息为您提供了有关您需要做什么的建议。你试过吗? Spring Boot 不会自动为您创建 JdbcTemplate bean,您需要自己创建。向您的 Spring Boot 应用程序类添加一个带有 @Bean 注释的方法,该方法返回一个 JdbcTemplate
  • @XtremeBaumer 我已经检查了依赖关系,没有任何遗漏。
  • @Jesper 谢谢你的想法。由于我是 Spring Boot 新手,我不知道该怎么做,请给我一些创建 Bean jdbctemplate 方法的示例

标签: java spring oracle jdbc spring-boot


【解决方案1】:

您需要定义一个JdbcTemplate 类型的Spring bean。您可以通过将@Bean 方法添加到创建并返回JdbcTemplate 的Spring Boot 应用程序类来做到这一点。例如:

@SpringBootApplication
public class ExampleApplication {

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

另外,如果您还没有这样做,您必须将数据库连接的属性添加到文件src/main/resources/application.properties。 Spring Boot 使用这些来创建 DataSource bean。例如(您需要在此处输入适当的值;这是使用 H2 内存数据库的示例):

spring.datasource.url=jdbc:h2:mem:demo
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

最后,您需要确保您对pom.xml 中的相应数据库驱动程序具有依赖关系。例如(对于 H2 数据库),您需要在 pom.xmldependencies 部分中有这个:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2018-02-19
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多