跳到主要内容

Maven

配置 Maven

本地缓存指向数据盘目录

~/.m2/settings.xml
<settings>
<localRepository>/data/maven</localRepository>
</settings>

使用 Maven 创建 Java 项目

mvn archetype:generate "-DgroupId=com.demo.hello" "-DartifactId=helloworld" "-DarchetypeArtifactId=maven-archetype-quickstart" "-DinteractiveMode=false"

下载依赖到本地缓存

mvn dependency:copy-dependencies

运行指定的 Main Class

mvn clean compile  # 先编译代码
mvn exec:java -Dexec.mainClass="com.demo.hello.App" # 通过exec指令执行mainClass
mvn exec:java -Dexec.mainClass="com.demo.hello.App" -Dexec.args="arg0 arg1 arg2" # 需要传递参数的话,通过-Dexec.args 指定

打包 jar

目标:

  1. 打包出来的 jar 可直接通过 java -jar xx.jar 运行,无需指定 mainClass。
  2. 将依赖包也一起打包,避免因环境中 classpath 里没安装相关依赖导致无法运行。

修改 pom.xml (注意高亮部分):

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.hello</groupId>
<artifactId>helloworld</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld</name>
<url>http://maven.apache.org</url>
<properties>
<!-- 指定 maven 编译时用的 jdk 版本,与 maven 基础镜像中的版本一致 -->
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
</properties>
<build>
<!-- 指定项目最终生成的 jar 文件名,如果是编译容器镜像,建议写上,将 jar 文件名固定下来,方便在 Dockerfile 中引用 -->
<finalName>hello</finalName>
<plugins>
<plugin>
<!-- 将项目源码编译成一个可执行 jar 包 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<!-- 运行 jar 包时运行的主类,要求类全名 -->
<mainClass>com.demo.hello.App</mainClass>
<!-- 是否指定项目 classpath 下的依赖 -->
<addClasspath>true</addClasspath>
<!-- 指定依赖的时候声明前缀 -->
<classpathPrefix>./lib/</classpathPrefix>
<!-- 依赖是否使用带有时间戳的唯一版本号,如:xxx-1.3.0-20121225.012733.jar -->
<useUniqueVersions>false</useUniqueVersions>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<!-- 利用 maven-dependency-plugin 把当前项目的所有依赖放到 target 目录下的 lib 文件夹下 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>

然后执行打包:

mvn clean package

最终 jar 包会在 target 目录下生成。