我有一个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添加依赖项?
5 回答
默认情况下,Spring Boot将您的JAR重新打包为可执行的JAR,它通过将所有类放在
BOOT-INF/classes
中,并将所有依赖库放在BOOT-INF/lib
中来实现 . 创建这个胖JAR的结果是你不能再将它用作其他项目的依赖项 .来自Custom repackage classifier:
如果要保留原始主工件以将其用作依赖关系,可以在
repackage
目标配置中添加classifier:使用此配置,Spring Boot Maven插件将创建2个JAR:主要的一个将与通常的Maven项目相同,而第二个将附加分类器并且是可执行的JAR .
@Tunaki所说的大部分是正确的,但根据你原来的问题,一个缺失的部分是:
这是因为从maven包装创建的FatJAR具有在特定位置指定的依赖库,这些库适用于Spring Boot如何执行应用程序 . 如果您只是将JAR添加到另一个应用程序的类路径中,那么您应该执行@Tunaki所说的内容,并将依赖的JAR文件包含到类路径中 . 处理此问题的最佳方法是使用Maven Dependency Plugin专门针对
dependency:copy-dependencies
mojo将所有依赖项下载到一个文件夹中,然后在编译其他应用程序时将其指定为库路径 .您可以通过maven-assembly-plugin扩展您的项目
构建完成后,您将获得3个 jar . 主要的一个将与通常的Maven项目相同,而第二个将具有附加exec的分类器并且是可执行的JAR . 第三个jar名称将附加jar-with-dependencies,并将包含你的类,其类在spring启动应用程序中添加为依赖项(spring-boot-starter-web,thymeleaf,...),因此进入pom在您希望将该项目添加为依赖项的应用程序中,您不必从spring boot项目添加依赖项 .
您可以设置项目,以便批处理启动程序依赖于jar,该jar将与您的其他应用程序共享 .
换句话说,根据您的初始要求:
假设你的jar是你的项目A,你的应用程序就是你的项目B.
现在,我建议你从A中移除发射部分;然后你将它放入一个新的项目C,它将嵌入Spring Boot,而这几乎完全依赖于A.
然后,由于A现在是一个简单的jar,B可以将它用作依赖 .
任何项目,如果你想要添加为依赖项,你需要该项目
<groupId>
,<artifactId>
,<version>
,您可以将这些项目作为依赖项添加到另一个模块或应用程序中,例如:您的应用程序pom详细信息你的依赖如下