spring boot下非web应用,mysql数据源报错问题

在非Web环境下的Spring Boot应用,启动时默认使用Tomcat数据源导致错误。解决办法是在@SpringBootApplication注解中取消自动配置,并在pom.xml添加Druid数据源依赖。此外,若出现找不到mysql.jdbc.Driver的问题,可能是因为未指定mysql-connector-java版本,需要在pom.xml中明确指定版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在非web应用下,spring boot启动时提示如下错误:

org.springframework.context.annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

spring boot启动时默认会自动配置数据源为org.apache.tomcat.jdbc.pool.DataSource。即使在配置文件或代码中指定了其他的数据源(如druid)。
解决方法是:在@SpringBootApplication注解中取消自动配置,如下:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ThisApplication
{
    public static void main( String[] args )
    {
        SpringApplication.run(ThisApplication.class);
    }
}

另外,pom.xml中加入依赖:

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

有时会出现ClassNotFoundException: com.mysql.jdbc.Driver。并且在IDEA Project Structure ->Modules ->Dependencies中有Maven:mysql:mysql-connector-java:unknown项。
解决在pom.xml指定mysql-connector-java的版本即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值