Search code examples
javaspringspring-bootjdbcflyway

Spring Boot + Flyway + AWS: Caused by: java.sql.SQLException: No suitable driver found


I get this except in AWS Elastic Beanstalk, but the app works locally.

01-Aug-2018 07:44:54.815 SEVERE [localhost-startStop-1] org.apache.catalina.core.ContainerBase.addChildInternal ContainerBase.addChild: start: 
 org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.api.FlywayException: Unable to obtain Jdbc connection from DataSource
Caused by: org.flywaydb.core.api.FlywayException: Unable to obtain Jdbc connection from DataSource
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://d-use1-xx.xxxxxxxxxxx.us-east-1.rds.amazonaws.com:3306/xxxxxxxxxxx

The JDBC URL is specified correctly. I have this in file.war/WEB-INF/classes/application.properties

spring.datasource.url = jdbc:mysql://d-use1-xx.xxxxxxxxxx.us-east-1.rds.amazonaws.com:3306/xxxxxxxxx
spring.datasource.username = xxxx
spring.datasource.password = xxxxxxxxx

I do have \WEB-INF\lib\mysql-connector-java-5.1.46.jar in the WAR file.

I don't know if it matters but I recently added a JDBC TokenStore for Spring Security OAuth2 and added this in the main class.

@SpringBootApplication
@MapperScan("com.xxxxxx.xxxxxx.mapper")
public class XxxxxxxxxxxxApplication extends SpringBootServletInitializer {

    @Bean(name = "OAuth")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

I don't know if it matters (never did before) but there was an empty environment variable set

01-Aug-2018 07:44:38.290 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -DJDBC_CONNECTION_STRING=


Solution

  • You need to add the spring.datasource.driver-class-name configuration property:

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

    JDBC automatic driver loading only works for drivers on the initial (system) class path of the application, but drivers located in WEB-INF/lib are added to a context class path at a later time and cannot be automatically loaded.

    This means you need to explicitly load them, which is what Spring Boot does if you specify spring.datasource.driver-class-name (or the environment variable SPRING_DATASOURCE_DRIVER_CLASS_NAME as you found out).