gpt4 book ai didi

java - 为什么我必须在 maven 项目中手动为 sql db 定义驱动程序

转载 作者:行者123 更新时间:2023-11-29 13:45:21 26 4
gpt4 key购买 nike

我在设置 maven 项目时遇到了问题,我创建了 springboot 应用程序,它连接到 postgres 数据库,所以我需要一个驱动程序,我在 maven 依赖项中以 3 种不同的方式指定了它:

  1. <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
    </dependency>
  2. <dependency> 
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.1-901-1.jdbc4</version>
    </dependency>
  3. <dependency> 
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.1</version>
    </dependency>

它们都不起作用,所以我必须通过项目 -> 属性 -> java 构建路径 -> 库 -> 添加外部 jar 在 STS(eclipse) 中通过项目属性指定它
并设置在 postgres jdcb jar 文件之前下载的路径,尽管它已经在 maven 依赖项中指定,因为我在 pom.xml 中留下了第一个 postgres 依赖项声明,所以现在驱动程序在 Maven 依赖项和引用库中定义,现在它正在工作,我不看不到错误:

Cannot load driver class: org.postgresql.Driver

但有趣的是我在我的另一台电脑上下载了这个项目,我不必手动指定驱动程序,maven 自己完成了这项工作。有人知道那是怎么发生的吗?

最佳答案

你在使用 SpringBoot maven 插件吗?它应该将所有必需的 jar 添加到类路径中。对于 postgres,您应该只需要这两个依赖项:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.1</version>
</dependency>
</dependencies>

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

您可以在此处找到示例 pom: https://spring.io/guides/gs/relational-data-access/

关于java - 为什么我必须在 maven 项目中手动为 sql db 定义驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com