Spring Boot + Flyway + AWS:原因:java.sql.SQLException:找不到合适的驱动程序

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

除了在 AWS Elastic Beanstalk 中,我得到这个,但该应用程序在本地运行。

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

JDBC URL 指定正确。我在 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

我在 WAR 文件中确实有 \WEB-INF\lib\mysql-connector-java-5.1.46.jar

我不知道这是否重要,但我最近为 Spring Security OAuth2 添加了一个 JDBC TokenStore,并在主 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();
    }

我不知道这是否重要(以前从来没有)但是有一个空的环境变量集

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

我可以通过设置环境变量来修复它

SPRING_DATASOURCE_DRIVER_CLASS_NAME=com.mysql.jdbc.Driver

AWS变成了

01-Aug-2018 17:01:03.505 INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Command line argument: -DSPRING_DATASOURCE_DRIVER_CLASS_NAME=com.mysql.jdbc.Driver

不知道为什么突然要求属性。我正在使用 flyway-core-3.2.1.jar。我没有在 https://flywaydb.org/documentation/plugins/springboot 中指定版本,所以它选择了这个版本。

您需要添加 spring.datasource.driver-class-name 配置 属性:

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

JDBC 自动驱动程序加载仅适用于应用程序初始(系统)class 路径上的驱动程序,但位于 WEB-INF/lib 中的驱动程序被添加到上下文 class 路径,不能自动加载。

这意味着您需要显式加载它们,如果您指定 spring.datasource.driver-class-name(或您发现的环境变量 SPRING_DATASOURCE_DRIVER_CLASS_NAME),这就是 Spring Boot 所做的。