Spring Boot错误——SpringBoot 2.0 报错: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

时间:2023-03-08 19:47:23

背景

  • 使用Spring Cloud搭建微服务,服务的注册与发现(Eureka)项目启动时报错,错误如下
    ***************************
    APPLICATION FAILED TO START
    *************************** Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

报错原因

  • 在网上找了解决方法,出现这个错误一般会是下面几种原因
    • 原因一:Spring Boot的配置,DataSourceAutoConfiguration会自动加载数据源
      • Spring boot 启动时会默认加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration这个类,DataSourceAutoConfiguration类使用了@Configuration注解向spring注入了dataSource bean。如果在项目配置文件中找不到数据源信息,项目在启动时就会报错
    • 原因二:在application.properties/或者application.yml文件中没有添加数据库配置信息
      • Spring Boot会自动加载classpath中配置文件中的数据源信息,如果找不到对应的数据源信息,就会报错
    • 因为我搭建的是 服务的注册与发现(Eureka)项目,项目中不需要进行数据源配置,所以报错的是原因一:Spring Boot配置中的DataSourceAutoConfiguration自动加载数据源,却找不到数据源信息导致的

解决方法

  • 在Spring Boot启动类加上注解@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}),代表在启动时不需要项目自动加载数据源即可
@EnableEurekaServer
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
  • Next