如何在另一个项目中向 Spring Boot Jar 添加依赖项?

新手上路,请多包涵

我有一个 Spring Boot 应用程序,并从中创建了一个 Jar。以下是我的 pom.xml

 <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
        <version>2.1.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!-- WebJars -->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

我想在我的其他应用程序中使用这个 Jar,所以将此 jar 添加到我的应用程序中。但是当我在那个 Jar 中调用一个方法时,它会抛出一个 ClassNotFoundException

我该如何解决这个问题?如何将依赖项添加到 Spring Boot JAR?

原文由 sparrow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
1 个回答

默认情况下,Spring Boot 将你的 JAR 重新打包成一个可执行的 JAR,它通过将所有类放入 BOOT-INF/classes 并将所有依赖库放入 BOOT-INF/lib 。创建这个胖 JAR 的后果是您不能再将它用作其他项目的依赖项。

自定义重新包装分类器

默认情况下, repackage 目标将用重新打包的工件替换原始工件。对于代表应用程序的模块来说,这是一种理智的行为,但是如果您的模块被用作另一个模块的依赖项,则需要为重新打包的模块提供分类器。

原因是应用程序类被打包在 BOOT-INF/classes 中,因此依赖模块无法加载重新打包的jar类。

如果您想保留原来的主工件以便将其用作依赖项,您可以在 repackage 目标配置中添加一个 classifier

 <plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <version>1.4.1.RELEASE</version>
  <executions>
    <execution>
      <goals>
        <goal>repackage</goal>
      </goals>
      <configuration>
        <classifier>exec</classifier>
      </configuration>
    </execution>
  </executions>
</plugin>

使用此配置,Spring Boot Maven 插件将创建 2 个 JAR:主要的 JAR 将与通常的 Maven 项目相同,而第二个将附加分类器并作为可执行 JAR。

原文由 Tunaki 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进