![](/img/trans.png)
[英]Running maven goals from Java without a Maven executable installed on the machine
[英]Calling Maven goals from Java
是否可以從Java調用Maven目標,例如,我是否可以執行以下操作:
mvn clean package
來自Java類?
謝謝,尼克
這很簡單 :)
Java代碼
MavenCli cli = new MavenCli();
cli.doMain(new String[]{"clean", "package"}, "project_dir", System.out, System.out);
項目配置:
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-embedder</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.aether</groupId>
<artifactId>aether-connector-wagon</artifactId>
<version>0.9.0.M2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http-lightweight</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
完整的工作示例: https : //github.com/mariuszs/maven-cli-example
我不建議使用MAVEN CLI
因為它與命令行替代方法的工作方式不同。 例如:
使用CLI,我想重現"mvn dependency:resolve validate"
cli.doMain(
new String[]{
"dependency:resolve", // download deps if needed
"validate"}, // just validates, no need even to compile
projectPath ...
但實際上它將遍布文件夾(遞歸)並將嘗試驗證那里的所有項目,即使我不想要它。 如果出現問題 - 它會失敗 。
但是,如果您嘗試僅使用命令行執行相同操作 - 它將僅調用pom.xm並將成功完成 (即使'projectPath'中的某些項目無法解析。
使用CLI
我無法使用“-f”標志來指定特定的pom.xml
!
這對我來說非常好:
private int resolveAsCommandLine() {
try {
String command = "mvn " +
"-f " + projectPath + "\\pom.xml " +
"-Dmaven.repo.local=" + localRepoPath + "\\repository " +
"-Dmaven.test.skip=true " + // ignore tests
"dependency:resolve " + // download deps if needed
"validate";
System.out.println("%> Executing command: '" + command + "'...");
Process p = Runtime.getRuntime().exec( // "cmd - for windows only"
"cmd /c " + command
);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
if(line.contains("[ERROR]")) return ERROR_STATUS;
if(line.contains("BUILD FAILURE")) return ERROR_STATUS;
if(line.contains("BUILD SUCCESS")) return OK_STATUS;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return ERROR_STATUS;
}
return ERROR_STATUS;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.