【问题标题】:Spring Boot connect to Postgres database on HerokuSpring Boot 连接到 Heroku 上的 Postgres 数据库
【发布时间】:2023-03-23 10:24:01
【问题描述】:

我一直在使用部署在 Heroku 上的 Spring Boot 应用程序,但我偶然发现了一个错误,我似乎无法找到解决方案。

我正在尝试按照 Heroku 教程 (link) 连接到 Postgres 数据库,但我一遍又一遍地收到此错误:

Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: 
Failed to instantiate [javax.sql.DataSource]:
Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: No supported DataSource type found

这是我正在使用的配置文件:

spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.removeAbandoned=true

还有 DatabaseConfig 类:

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

谁能指出我正确的方向。我做错了什么?

【问题讨论】:

  • 您好,您是否为 PostGreSQL JDBC 驱动程序 (pom.xml) 正确添加了 Maven 依赖项? <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.4-1201-jdbc4</version> </dependency>
  • 是的 - 我还添加了 Maven 依赖项
  • 您是否使用 Heroku 命令行创建并绑定到 PostgreSQL 服务? $ heroku 插件:添加 heroku-postgresql:hobby-dev
  • 是的 - 我已经按照教程中的步骤进行操作。感谢@Georgesvanhoutte 看一看。我被这个错误困住真的很令人沮丧:(
  • 我去年在 heroku 上苦苦挣扎。忘了它。在我们的命令行中使用带有 Spring 工具套件的关键云代工。效果很好。

标签: spring postgresql heroku spring-boot


【解决方案1】:

我遇到了同样的问题并设法解决了它。这个问题不是 Heroku 特有的,因为它可以通过在本地运行应用程序以及使用相同的配置来重现。

根据堆栈跟踪,很明显在类路径中没有找到数据源。根据 Spring Boot 文档,找到 here,可以使用 spring-boot-starter-jdbcspring-boot-starter-data-jpa 自动获取 tomcat-jdbc,这似乎是 Spring Boot 中的首选。

我在pom.xml中添加了如下依赖,问题解决了:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 2022-08-18
    • 2021-06-21
    • 2016-08-12
    • 1970-01-01
    • 2020-05-31
    • 2012-06-08
    • 2014-05-28
    • 2021-02-06
    相关资源
    最近更新 更多