[Fixed] Spring Boot Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class – Spring-boot

by
Ali Hasan
jar spring-boot

Quick Fix: Use maven deploy instead of Intellij to generate the jar file, as it ensures all required dependencies are included and the application.properties is read correctly.

The Problem:

The Spring Boot application fails to run when built into a JAR file, due to the factory method ‘dataSource’ in ‘DataSourceConfiguration$Hikari’ failing to determine a suitable driver class. The application connects to a MySQL database and the relevant properties are configured in the application.properties file. The issue persists despite cleaning the local Maven repository (.m2 folder) and running ‘maven clean’ and ‘maven install’ commands.

The Solutions:

Solution 1: Use Maven Deploy to Generate Jar File

Instead of using IntelliJ’s “Build -> Build Artifacts” feature to generate the JAR file, use Maven’s “mvn deploy” command. This ensures that the correct JAR file is generated with all necessary dependencies included.

Solution 2: Verify MySQL Connector JAR Dependency

Ensure that the MySQL connector JAR dependency is correctly defined in the project’s pom.xml file. The correct dependency for MySQL Connector should be:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

Q&A

I am trying to build a jar file of a spring boot project that uses maven. I am using Intellij IDE, and when I run the project on Intellij, it runs without issues.

So, after a lot of research and hair pulling I realized the application.properties is not being read when using Intellij IDE to create the jar file.

The issue is when I create a .jar file and try to run the application I get the following error?

This error occurred and other errors as I was testing different approaches, because I generated the jar through Intellij (Build -> Build Artifacts. ) instead of using maven.

Do you have a correct pom.xml dependency addition?

You have a small typo in pom.xml. This is the correct one:

Video Explanation:

The following video, titled "Factory Design Pattern in Spring boot app - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this video I have implemented Factory design pattern in spring boot and explained best practices of implementing Factory design.