[Fix] Spring Boot - IllegalStateException: Cannot load driver class: com.mysql.cj.jdbc.Driver


Exception Stacktrace:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)

ERROR 5614 --- [main] o.s.boot.SpringApplication : Application run failed

Caused by: org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name 'dataSource' defined in class path resource 
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: 
Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' 
threw exception with message: Cannot load driver class: com.mysql.cj.jdbc.Driver

Caused by: java.lang.IllegalStateException: Cannot load driver class: com.mysql.cj.jdbc.Driver

If you get this above exception when you try to run a Spring Boot application, the reason for this is that you have missed adding the dependency for MySQL driver.

gradle.build

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter'
  runtimeOnly 'com.mysql:mysql-connector-j'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Maven: pom.xml

<dependencies>
    <!-- Other dependencies -->

    <!-- MySQL Connector/J as a runtime-only dependency -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap