SpringBoot+Druid报错Failed to determine a suitable driver class的解决

柔光的暖阳◎ 2022-05-16 00:55 666阅读 0赞

问题描述

项目中使用了自定义的Spring Listener配置,从网络获取配置KV,在SpringBoot启动过程中加载,然后再加载Druid环境。程序启动时-间歇性报错(三次启动可能有一次报错,其他两次可以正常启动):

  1. ***************************
  2. APPLICATION FAILED TO START
  3. ***************************
  4. Description:
  5. Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
  6. Reason: Failed to determine a suitable driver class
  7. Action:
  8. Consider the following:
  9. If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
  10. If you have database settings to be loaded from a particular profile you may need to activate it (the profiles de are currently active).

分析

根据日志显示,DruidDataSourceWrapper(implements InitializingBean )类加载时,配置信息还没有就位。
Druid没有读取到数据库配置,所以引发了上面的报错。

仔细看代码时发现,项目中有两个类继承了:SpringBootServletInitializer,其中一个类并没有加载自定义的那个ApplicationListener。既然有两个SpringBootServletInitializer,这两个应该都加载ApplicationListener,获取只保留一个。

  • 需要确保Druid在读取配置时,自定义的Listener已经把配置信息加载好了。

解决

由于项目启动时,用的是外部Tomcat启动的方式。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-tomcat</artifactId>
  4. <scope>provided</scope>
  5. </dependency>

所以,在继承自SpringBootServletInitializerServletInitializerconfigure方法中,需要使用application.listeners(),加载自定义的ApplicationListener

部分源码:

  1. @Override
  2. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  3. // 自定义的ApplicationListener
  4. application.listeners(buildListener("ServletInitializer"));
  5. return application.sources(RabiesVaccineApplication.class);
  6. }

ApplicationListenerInitializingBean前被加载,保证Druid可以读取到配置信息,问题解决。

环境

  • spring-boot-starter-parent:2.0.4.RELEASE
  • druid-spring-boot-starter:1.1.10
  • druid:1.1.10
  • jdk:1.8

发表评论

表情:
评论列表 (有 0 条评论,666人围观)

还没有评论,来说两句吧...

相关阅读