小编典典

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

spring-boot

我有一个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添加依赖项?


阅读 376

收藏
2020-05-30

共1个答案

小编典典

默认情况下,Spring Boot将您的JAR重新打包为可执行的JAR,并通过将您所有的类放入其中BOOT- INF/classes,并将所有相关库放入其中来实现BOOT-INF/lib。创建此胖JAR的结果是您不能再将其用作其他项目的依赖项。

自定义重新包装分类器

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

这样做的原因是,应用程序类被打包在其中,BOOT-INF/classes以便从属模块无法加载重新打包的jar的类。

如果要保留原始的主要工件以将其用作依赖项,则可以classifierrepackage目标配置中添加一个:

<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:主要的将与通常的Maven项目相同,而第二个将附加分类器并成为可执行的JAR。

2020-05-30