【问题标题】:Is it mandatory to configure DataSource in Spring starter project?在 Spring starter 项目中是否必须配置 DataSource?
【发布时间】:2020-10-26 04:05:19
【问题描述】:

我想创建一个基本的 Spring 启动应用程序并发出 get 请求。我已经添加了 Spring JPA、Spring Web 依赖项并开始在端口 8080 中运行,但我的应用程序要启动。它说 " 说明:

未能配置数据源:未指定“url”属性并且无法配置嵌入式数据源。 原因:无法确定合适的驱动程序类“。

我没有添加任何数据库依赖项,因为我不需要它,在我的项目中是否必须具有数据库依赖项? 这是我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>

4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.1.发布 com.example java-示例项目 0.0.1-快照 java-示例项目 Spring Boot 演示项目

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

【问题讨论】:

  • 您正在包括 JPA。如果没有数据库,您将如何使用 JPA?

标签: java mysql spring spring-boot web


【解决方案1】:

您的 POM 中可能存在数据依赖项:(或 build.gradle)

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
  <version>2.3.1.RELEASE</version>
</dependency>

如果是这样,请删除它。

【讨论】:

    【解决方案2】:

    如果您包含 Spring JPA,那么是的,它是强制性的。

    但您可以轻松禁用 Spring 自动配置:

    spring.autoconfigure.exclude=
      org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \
      org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \
    org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
    

    【讨论】:

    • 这是一种解决方法。如果不需要 JPA(或 DB 访问),则根本不应该包含它。
    【解决方案3】:

    是的,这是强制性的。但是,如果您不想运行真正的数据库,请使用内存数据库 H2。只需将 com.h2database:h2 添加到依赖项即可。

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 1970-01-01
      • 2020-10-27
      • 2015-02-06
      • 2022-10-05
      • 2015-05-25
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      相关资源
      最近更新 更多