Spring Boot连接PostgreSQL失败,请求排查原因
Hey there, let's dig into why your Spring Boot app can't establish a connection to PostgreSQL. Based on your error logs and configurations, here are the key issues and fixes you can try:
1. 配置文件URL存在多余空格
Take a look at your application.properties database URL:
spring.datasource.url= jdbc:postgresql://localhost:5432/springbootdb
The space right after the equals sign will break URL parsing. Remove it to fix the format:
spring.datasource.url=jdbc:postgresql://localhost:5432/springbootdb
2. 重复且版本不兼容的PostgreSQL依赖
Your pom.xml has duplicate PostgreSQL dependencies, and the specified version is too old for your Spring Boot version:
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.4-1206-jdbc42</version> </dependency>
Spring Boot 2.2.6.RELEASE comes with a default compatible PostgreSQL driver version (42.2.12), but your manually set 9.4 version is outdated and can cause conflicts with HikariCP (the default connection pool) and JPA.
Fix: Delete the duplicate version-specific dependency, and keep only the managed one (add runtime scope for better practice):
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
3. 基础数据库连接验证
Let's rule out the basics:
- Check if PostgreSQL is running: Make sure your local PostgreSQL service is started, and it's listening on port 5432 (the default). If you changed the port, update it in your URL.
- Verify user credentials & permissions: Confirm the
rootuser exists in PostgreSQL, the passwordrootis correct, and this user has access to thespringbootdbdatabase. Also, check yourpg_hba.conffile to ensure localhost connections are allowed for this user (using md5 authentication). - Confirm the database exists: Double-check that the
springbootdbdatabase is actually created in PostgreSQL, and its owner is indeed therootuser.
4. Connection Pool Compatibility
Your HikariCP version (3.4.2) is compatible with Spring Boot 2.2.6, but the outdated PostgreSQL driver was likely causing the connection pool to fail creating connections. Fixing the dependency version should resolve this.
内容的提问来源于stack exchange,提问作者Boommeister

