Springboot + MySQL + Driver Class Not Found

Viewed 1458

I'm doing a simple spring boot project with a thread pool and MySQL in order to connect to MySQL whenever I'm adding spring-boot-starter-jdbc I'm getting below error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.s

Update 1:

    <dependencies>
            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>3.3</version>
</dependency>

    </dependencies>
4 Answers

It seems like you are missing mysql-connector dependency, Add these to your pom.

Maven:

   <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

or gradle:

compile "mysql:mysql-connector-java:*"

Looks like you forget to add dependency to MySQL (Spring Boot is using H2 database by default), you should add next lines to your pom.xml:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

First include this in your pom file.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Second, clean install the maven project. If you are using eclipse check your JDK version and maven (Sometime jre is used instead of jdk, so, though in console everything looks fine but acutally the jar is not downloaded) in short .m2 repo should have this jar file when maven build is done.

Scope "runtime" is good for unit test and container as tomcat etc. when container provide jdbc driver. When run standalone apps (spring-boot) you should remove it or set to "compile".

Related