是否可以从Java调用Maven目标,例如,我可以做相同的:
mvn clean package
来自Java类?
感谢, 尼克
答案 0 :(得分:19)
答案 1 :(得分:2)
这很简单:)
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>
答案 2 :(得分:1)
我不建议使用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'中的某些项目无法解析。< / p>
使用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;
}