Fix: Spring Boot Failed to Configure DataSource (DataSource Auto-Configuration Error)
Quick Answer
How to fix Spring Boot 'Failed to configure a DataSource' errors — missing URL property, driver class not found, connection refused, and how to correctly configure datasource properties for MySQL, PostgreSQL, and H2.
The Error
Spring Boot fails to start with:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource
could be configured.
Reason: Failed to determine a suitable driver classOr with a specific driver error:
Unable to determine Tomcat connection pool library.
java.lang.RuntimeException: Driver com.mysql.cj.jdbc.Driver claims to not accept jdbcUrlOr a connection error at startup:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure — Last packet sent to the server was 0 ms ago.Or:
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException:
Failed to determine a suitable driver classWhy This Happens
Spring Boot auto-configures a DataSource when it finds a database driver on the classpath. The auto-configuration requires at minimum a spring.datasource.url property. Failures occur when:
spring.datasource.urlis missing or empty — the most common cause. Spring Boot cannot guess the database URL.- Database driver not on the classpath — the JDBC driver dependency is missing from
pom.xmlorbuild.gradle. - Wrong JDBC URL format — the URL does not match the driver’s expected format.
- Database server is not running or not reachable — connection refused at startup.
- Wrong credentials — the username/password in properties does not match the database user.
- Spring Data JPA on classpath without a database configured — adding
spring-boot-starter-data-jpatriggers DataSource auto-configuration; if you do not need a database, exclude it.
Fix 1: Add the Required datasource Properties
The minimum required configuration:
# src/main/resources/application.properties
# PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.driver-class-name=org.postgresql.Driver
# MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# H2 in-memory (for development/testing)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=trueYAML format:
# src/main/resources/application.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb
username: myuser
password: mypassword
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialectNote:
driver-class-nameis optional when the JDBC URL prefix matches a known driver on the classpath. Spring Boot infers the driver fromjdbc:postgresql://→ PostgreSQL driver,jdbc:mysql://→ MySQL driver, etc. Specify it explicitly if auto-detection fails.
Fix 2: Add the JDBC Driver Dependency
If the driver is not on the classpath, Spring Boot cannot connect regardless of properties.
Maven — add to pom.xml:
<!-- PostgreSQL -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- H2 (in-memory, for tests) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>Gradle — add to build.gradle:
dependencies {
// PostgreSQL
runtimeOnly 'org.postgresql:postgresql'
// MySQL
runtimeOnly 'com.mysql:mysql-connector-j'
// H2 (tests only)
testRuntimeOnly 'com.h2database:h2'
}After adding the dependency, run:
# Maven
mvn clean install
# Gradle
./gradlew dependencies | grep -i postgresqlFix 3: Fix JDBC URL Format
Each database requires a specific URL format:
PostgreSQL:
# Standard
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
# With SSL
spring.datasource.url=jdbc:postgresql://host:5432/mydb?sslmode=require
# Cloud SQL (GCP)
spring.datasource.url=jdbc:postgresql:///mydb?cloudSqlInstance=project:region:instance&socketFactory=com.google.cloud.sql.postgres.SocketFactoryMySQL:
# MySQL 8.x — use CJ driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
# Common parameters to add when you see connection errors:
# useSSL=false — disable SSL for local dev
# serverTimezone=UTC — required by MySQL Connector/J 8.0+
# allowPublicKeyRetrieval=true — required for some MySQL 8 auth configurationsSQL Server:
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=mydb;encrypt=false
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriverH2 (file-based instead of in-memory):
spring.datasource.url=jdbc:h2:file:./data/mydb;AUTO_SERVER=TRUEFix 4: Use Environment Variables for Credentials
Hardcoding credentials in application.properties is a security risk. Use environment variables or a secrets manager:
# application.properties — references environment variables
spring.datasource.url=${DATABASE_URL}
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}# Set environment variables before running
export DATABASE_URL=jdbc:postgresql://localhost:5432/mydb
export DATABASE_USERNAME=myuser
export DATABASE_PASSWORD=secret
java -jar app.jarSpring Boot also reads from .env via system properties at runtime:
java -DDATABASE_URL=jdbc:postgresql://localhost:5432/mydb -jar app.jarFor different environments — use Spring profiles:
# application.properties (defaults)
spring.profiles.active=dev
# application-dev.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
# application-prod.properties
spring.datasource.url=${DATABASE_URL}
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}# Activate a profile at runtime
java -Dspring.profiles.active=prod -jar app.jar
# Or:
SPRING_PROFILES_ACTIVE=prod java -jar app.jarFix 5: Exclude DataSource Auto-Configuration When Not Needed
If you added spring-boot-starter-data-jpa or spring-boot-starter-jdbc but do not actually need a database (e.g., you use MongoDB only), exclude the DataSource auto-configuration:
// Main application class
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}Or via properties:
spring.autoconfigure.exclude=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurationFix 6: Fix Connection Pool Configuration
Spring Boot uses HikariCP by default. Connection pool exhaustion causes startup failures or slow queries at runtime:
# HikariCP connection pool settings
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000 # 30 seconds
spring.datasource.hikari.idle-timeout=600000 # 10 minutes
spring.datasource.hikari.max-lifetime=1800000 # 30 minutes
spring.datasource.hikari.connection-test-query=SELECT 1
# For PostgreSQL — use pgBouncer URL with transaction mode
# spring.datasource.hikari.connection-init-sql=SET search_path TO myschemaDiagnose pool exhaustion:
# Enable HikariCP logging
logging.level.com.zaxxer.hikari=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUGFix 7: Test the Connection Outside Spring Boot
If Spring Boot cannot connect, verify the connection parameters are correct first:
# Test PostgreSQL connection with psql
psql -h localhost -p 5432 -U myuser -d mydb
# Test MySQL connection
mysql -h localhost -P 3306 -u myuser -pmypassword mydb
# Test if the port is reachable
nc -zv localhost 5432
telnet localhost 5432Simple Java connection test (without Spring):
import java.sql.Connection;
import java.sql.DriverManager;
public class TestConnection {
public static void main(String[] args) throws Exception {
String url = "jdbc:postgresql://localhost:5432/mydb";
String user = "myuser";
String password = "mypassword";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected: " + conn.getMetaData().getDatabaseProductName());
}
}
}Still Not Working?
Check the full stack trace. The Failed to configure a DataSource message is often a wrapper — the root cause is further down:
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)Connection refused means the database server is not running or not listening on the expected port. Check:
# PostgreSQL
sudo systemctl status postgresql
sudo -u postgres psql -c '\l'
# MySQL
sudo systemctl status mysql
mysql -u root -pCheck if the database exists. Spring Boot connects to a specific database — if the database does not exist, the connection fails even if the server is running:
-- PostgreSQL
CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser;
-- MySQL
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;Check Flyway or Liquibase migration failures. If you use database migration tools, a failed migration prevents Spring Boot from starting. Check the migration logs and the flyway_schema_history table for failed entries.
For related Spring Boot and Java database issues, see Fix: Spring Boot WhiteLabel Error Page and Fix: MySQL Access Denied for User.
Solo developer based in Japan. Every solution is cross-referenced with official documentation and tested before publishing.
Was this article helpful?
Related Articles
Fix: Hibernate LazyInitializationException — Could Not Initialize Proxy
How to fix Hibernate LazyInitializationException — loading lazy associations outside an active session, fetch join, @Transactional scope, DTO projection, and Open Session in View.
Fix: Spring Boot "The dependencies of some of the beans in the application context form a cycle"
How to fix Spring Boot circular dependency errors — BeanCurrentlyInCreationException, refactoring to break cycles, @Lazy injection, setter injection, and @PostConstruct patterns.
Fix: Spring Security Returning 403 Forbidden Unexpectedly
How to fix Spring Security 403 Forbidden errors — CSRF token missing, incorrect security configuration, method security blocking requests, and how to debug the Spring Security filter chain.
Fix: Spring BeanCreationException: Error creating bean with name
How to fix Spring BeanCreationException error creating bean caused by missing dependencies, circular references, wrong annotations, configuration errors, and constructor issues.