报错:Failed to determine a suitable driver class; Error creating bean with name ‘dataSource’ defined in class path resource; Factory method ‘dataSource’ threw exception 让spring boot项目启动时不连接数据库

背景:新建一个项目,启动后遇到这个问题。提示数据库配置异常,但我这个项目并没有用到数据库。

可能原因:参考自https://blog.csdn.net/qq_41701723/article/details/128949331

pom.xml 配置文件中配置了数据连接技术 spring-boot-starter-jdbc 包 。在启动配置文件时 ,Spring Boot 的自动装配机制就会去配置文件中寻找相关的数据库的连接配置信息,如果找不到则抛出异常信息。

以下为报错信息解决方法

报错信息

image-20241209233135832

Error creating bean with name 'dataSource' defined in class path resource[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration H i k a r i . c l a s s ] : ‘ B e a n i n s t a n t i a t i o n v i a f a c t o r y m e t h o d f a i l e d ‘ ; n e s t e d e x c e p t i o n i s o r g . s p r i n g f r a m e w o r k . b e a n s . B e a n I n s t a n t i a t i o n E x c e p t i o n : ‘ F a i l e d t o i n s t a n t i a t e ‘ [ c o m . z a x x e r . h i k a r i . H i k a r i D a t a S o u r c e ] : ‘ F a c t o r y m e t h o d ′ d a t a S o u r c e ′ t h r e w e x c e p t i o n ‘ ; n e s t e d e x c e p t i o n i s o r g . s p r i n g f r a m e w o r k . b o o t . a u t o c o n f i g u r e . j d b c . D a t a S o u r c e P r o p e r t i e s Hikari.class]: `Bean instantiation via factory method failed`; nested exception is org.springframework.beans.BeanInstantiationException: `Failed to instantiate` [com.zaxxer.hikari.HikariDataSource]: `Factory method 'dataSource' threw exception`; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties Hikari.class]:Beaninstantiationviafactorymethodfailed;nestedexceptionisorg.springframework.beans.BeanInstantiationException:Failedtoinstantiate[com.zaxxer.hikari.HikariDataSource]:FactorymethoddataSourcethrewexception;nestedexceptionisorg.springframework.boot.autoconfigure.jdbc.DataSourcePropertiesDataSourceBeanCreationException: Failed to determine a suitable driver class

解决方法参考自:https://blog.csdn.net/qq_41701723/article/details/128949331

https://www.cnblogs.com/panchanggui/p/14715032

方法①:在程序入口文件中为@SpringBootApplication添加属性 “ exclude=DataSourceAutoConfiguration.class ”,这种用法是在告诉 Spring Boot 在自动配置的过程中排除 DataSourceAutoConfiguration 类。这样就可以在 SpringBoot 应用程序启动时,排除 jdbc 的自动装配机制。

image-20241209234643167

方法②:在程序入口文件中添加@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}),和上面的方法等价。

image-20241209235701802


拓展:@SpringBootApplication注解和@EnableAutoConfiguration注解的关系

  1. @SpringBootApplication 注解:这是一个组合注解,它包含了 @EnableAutoConfiguration@Configuration@ComponentScan。通过在 @SpringBootApplication 注解中使用 exclude 属性,可以直接排除不需要的自动配置类,如 DataSourceAutoConfiguration。这种方式简单直观,适用于大多数情况。
  2. @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 注解:这种方式是单独使用 @EnableAutoConfiguration 注解,并指定 exclude 属性来排除特定的自动配置类。这种方式更加灵活,允许在不使用 @SpringBootApplication 的情况下进行更细粒度的控制。

在 Spring Boot 应用启动时排除 DataSourceAutoConfiguration 的自动配置,两种方式都可以达到相同的效果。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐