【问题标题】:Spring Boot & PostgreSQL- HikariCP always returns nullSpring Boot 和 PostgreSQL-HikariCP 总是返回 null
【发布时间】:2019-07-12 19:47:54
【问题描述】:

我正在尝试创建一个没有 JPA / Hibernate 的 Spring Boot 应用程序(由于数据库结构复杂,因此我需要对查询进行更多控制)

我在让 DataSource 工作时遇到了一些问题,它只返回 Null 而不是 DataSource。

这些是我的 Pom.xml 依赖项:

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.5</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

这是application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username= postgres
spring.datasource.password = postgres
spring.datasource.driverClassName = org.postgresql.ds.PGSimpleDataSource
spring.datasource.dataSourceClassName = org.postgresql.ds.PGSimpleDataSource

这是我的连接类返回数据源:

@Configuration
@PropertySource({"classpath:application.properties"})
public class Conn {

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

}

这是我尝试创建连接的 RequestHandler(现在正在记录,它总是返回 null)。

@RestController
public class Test implements ErrorController {

    private DataSource ds;
    private static final String PATH = "/error";


    @RequestMapping("/connectToDb")
    public void doSomething() {
        ds = new Conn().dataSource();
        System.out.println(ds);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }

}

每当我尝试将实际的 DataSource 用于准备好的语句时,我都会收到错误消息:

HikariPool-1 - dataSource or dataSourceClassName or jdbcUrl is required.

一直在尝试更改 application.properties 并尝试不同的方法,但到目前为止没有任何效果。我发现的类似帖子也有相同的错误消息,但我还没有找到解决问题的方法。

对此有何意见? 谢谢。

【问题讨论】:

  • 您正在创建Conn 的新实例。你需要自动装配它。
  • 考虑使用Spring Data JPA 来处理数据库。顺便说一句,你不需要手动创建DataSource,因为它已经通过 Spring Boot 的自动配置机制为你创建了。

标签: java spring postgresql spring-boot datasource


【解决方案1】:

问题来了

@RestController
public class Test implements ErrorController {

    @RequestMapping("/connectToDb")
    public void doSomething() {
        ds = new Conn().dataSource(); // <<<<<
        System.out.println(ds);
    }
}

您不能简单地创建配置的新实例。如果你这样做,那么你基本上忽略了所有的注释。您特别需要 Spring 已经创建的实例,您可以通过自动装配来完成。

不过,您无需传递整个配置,只需自动装配该 bean。

@RestController
public class Test implements ErrorController {

    private final DataSource ds;
    private static final String PATH = "/error";

    public Test(DataSource ds) {
        this.ds = ds;
    }

    @RequestMapping("/connectToDb")
    public void doSomething() {
        System.out.println(ds);
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}

【讨论】:

  • 哇,好简单!谢谢!奇迹般有效。感谢您通过使用自动装配让我意识到我根本不需要 Conn 类 :)