Martyn
Martyn

Reputation: 6383

Could not load JDBC driver class [com.mysql.cj.jdbc.Driver]

I've got the following class in my Spring Boot app:

@Configuration
public class JDBCTokenConfig {

    ...

    @Value("${spring.datasource.driver-class-name}")
    private String dbDriverClassName;

    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(dbDriverClassName);
        dataSource.setUrl(datasourceUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }

I've also got the following in my pom.xml:

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

In my application.properties I have:

...
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Yet I'm seeing the following error:

Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [com.mysql.cj.jdbc.Driver]

Is this the correct the drive class path? Or anything else?

Upvotes: 1

Views: 2950

Answers (1)

R.G
R.G

Reputation: 7121

Try using com.mysql.jdbc.Driver

Spring uses the following preconfigured versions for dependencies when a version is not explicitly provided in the pom.xml: https://docs.spring.io/platform/docs/current/reference/htmlsingle/#appendix-dependency-versions

Here the following version of mysql-connector-java will be used . 5.1.47

For mysql-connector-java v5.1.47 the correct driver class is com.mysql.jdbc.Driver

You could also provide the dependency with version to use the latest driver : com.mysql.cj.jdbc.Driver

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

Upvotes: 4

Related Questions