Maven打包后将JAR包放到指定位置的五种方法

作者:十万个为什么2024.01.17 07:34浏览量:19

简介:介绍五种常用的方法,将Maven打包后的JAR包放置到指定位置。包括直接拷贝、使用Maven的resources插件、使用Maven的assembly插件、使用Maven的exec插件和编写自定义的Maven插件。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

在Maven项目中,我们经常需要将打包后的JAR包放置到特定的位置。以下是五种常用的方法来实现这个目标:
方法一:直接拷贝
最简单的方法是直接将打包后的JAR文件从target目录拷贝到目标位置。可以使用命令行或文件管理器完成此操作。
方法二:使用Maven的resources插件
在项目的pom.xml中,可以配置resources插件来指定JAR包的输出位置。例如:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-resources-plugin</artifactId>
  6. <version>3.2.0</version>
  7. <configuration>
  8. <outputDirectory>${project.build.directory}/custom-location</outputDirectory>
  9. </configuration>
  10. </plugin>
  11. </plugins>
  12. </build>

这段配置会将打包后的JAR包放在target/custom-location目录下。
方法三:使用Maven的assembly插件
Maven的assembly插件允许你创建自定义的构建输出。你可以创建一个assembly描述文件(通常是assembly.xml),在其中指定JAR包的输出位置。然后,在pom.xml中配置maven-assembly-plugin来使用这个描述文件。例如:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <artifactId>maven-assembly-plugin</artifactId>
  5. <configuration>
  6. <descriptor>assembly.xml</descriptor>
  7. </configuration>
  8. <executions>
  9. <execution>
  10. <id>make-assembly</id>
  11. <phase>package</phase>
  12. <goals>
  13. <goal>single</goal>
  14. </goals>
  15. </execution>
  16. </executions>
  17. </plugin>
  18. </plugins>
  19. </build>

assembly.xml文件中,可以指定JAR包的输出路径。例如:

  1. <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" ... >
  2. ...
  3. <id>jar-with-dependencies</id>
  4. ...
  5. <files>
  6. <fileMode>0644</fileMode>
  7. <fileLinksToCopyEmptyDirectories>false</fileLinksToCopyEmptyDirectories>
  8. <file>${project.build.directory}/custom-location/my-app.jar</file>
  9. </files>
  10. ...
  11. </assembly>

这将把JAR包放在target/custom-location目录下。
方法四:使用Maven的exec插件
Maven的exec插件允许你运行外部命令或脚本。你可以编写一个简单的脚本来将JAR包移动到目标位置,并在pom.xml中配置exec插件来执行这个脚本。例如:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.codehaus.mojo</groupId>
  5. <artifactId>exec-maven-plugin</artifactId>
  6. <version>2.6.1</version>
  7. <configuration>
  8. <mainClass>com.example.MainClass</mainClass>
  9. <arguments>
  10. <argument>arg1</argument>
  11. <argument>arg2</argument>
  12. </arguments>
  13. <executions>
  14. <execution>
  15. <id>move-jar</id>
  16. <phase>package</phase>
  17. <goals>
  18. <goal>exec</goal>
  19. </goals>
  20. <configuration>
  21. <executable>mv</executable>
  22. <arguments>
  23. <argument>${project.build.directory}/${project.artifactId}-${project.version}.jar</argument>
  24. <argument>${project.build.directory}/custom-location/</argument>
  25. </arguments>
  26. </configuration>
  27. </execution>
  28. </executions>
  29. </configuration>
  30. </plugin>
  31. </plugins>
  32. </build>

这将把J

article bottom image

相关文章推荐

发表评论