我正在开发一个将包含在其他项目(项目 B、项目 C ...)中的 spring boot 项目(项目 A)。我在项目A中有几个依赖,但是在导入项目A的项目中,可能需要一些或只需要一个。 我试图找到一种方法来在打包项目 A 时排除 jar 依赖项,以便项目 B 在运行时提供所需的依赖项。当项目 A 出于测试目的独立运行时,我希望有可用的依赖项。
已经尝试过以下
我试过使用:
<scope>provided</scope>
<optional>true</optional>
jar 最终还是出现在了最终的 Artifact 中。
还尝试将以下内容添加到 spring-boot-maven-plugin
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<excludeArtifactIds>spring-boot-starter-redis</excludeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
这只会删除 spring-boot 依赖项,但此依赖项的子项的 jar 仍会在最终 Artifact 中结束。
最佳答案
在我们当前的项目中,我们需要为应用程序创建一个 war 文件,该文件必须部署在 JEE 服务器中。 war 文件必须只包含所需的 jar 文件,不包含 JEE 服务器已经提供的任何 API 或实现。
但是,我们希望保留生成可执行 war 或 jar 文件的可能性,如 Boot 默认提供的那样,用于测试目的。
为实现它,我们已将所有可选依赖项设置为提供。比如我们在开发中有一些直接依赖,比如JDBC驱动,我们不想包含在部署的war文件中。还有一些引导主启动器,它们提供与 JEE 服务器中不需要的其他启动器和库的依赖关系。 spring-boot-starter-tomcat 和 spring-boot-starter-jdbc 启动程序就是这种情况。在我们的项目中,我们的 pom.xml 文件中有以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<scope>provided</scope>
</dependency>
这样,这些依赖项将不会包含在原始 jar/war 文件中,但 spring boot maven 插件会将它们包含在重新打包的 jar/war 的 lib-provided 文件夹中。
这些依赖项不会被 JEE 服务器看到,但会使打包的应用程序比需要的更大。解决办法是告诉spring boot maven插件用其他名称创建重新打包的文件,同时排除开发工具:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>${start-class}</mainClass>
<classifier>exec</classifier>
</configuration>
</plugin>
这样maven会为你的应用生成两个包:
- 默认的 jar/war 包,没有所有提供的依赖项。
- 一个重新打包的文件,其名称以 _exec.jar/.war 结尾,所有提供的依赖项都在 lib-provided 文件夹中,并支持使用 java -jar 文件< 运行应用程序/em>
在您的情况下,您可以使用相同的技术来生成要包含在项目 B 中的项目 A 的包,以及要作为独立运行的项目 A 的包。
如果您不需要为项目 A 创建独立运行的包,并且只在您的 IDE 中测试它,您甚至可以从您的 pom.xml.
关于java - Spring 启动 : Exclude dependencies on packaging,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37961730/