【发布时间】: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