可能有两种方法可以实现。
方法 1:以编程方式 - 使用 maven 的库
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
Artifact artifact = new DefaultArtifact(groupId, artifactId, version,
null, extension, classifier, new DefaultArtifactHandler(extension));
ArtifactRepositoryLayout layout = new DefaultRepositoryLayout();
String artifactPath = layout.pathOf(artifact);
有依赖关系:
<!-- https://mvnrepository.com/artifact/org.apache.maven/maven-artifact -->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>3.8.4</version>
</dependency>
一般来说,上面的代码使用maven的内置代码来获取artifact到本地仓库根目录的相对路径。
限制:这不适用于RELEASE 或LATEST 等伪版本
方法2:使用虚拟项目和dependency:list目标
这种方法权重更大,不是程序化的,但适用于所有场景。
首先,创建一个一次性的 pom.xml,如:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>dummy</groupId>
<artifactId>dummy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<!-- artifact information here -->
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
</project>
然后,在上述pom.xml的父目录下运行如下命令:
mvn -B dependency:list -DoutputAbsoluteArtifactFilename=true -DexcludeTransitive=true | \
grep -FA1 'The following files have been resolved:' | \
tail -n 1 | \
cut -d ':' -f6
你会得到:
/home/vivimice/.m2/repository/org/slf4j/slf4j-api/2.0.0-alpha5/slf4j-api-2.0.0-alpha5.jar