1.Maven Invoker
引入相关依赖
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>3.0.1</version>
</dependency>
编写测试代码
public static void main(String[] args) {
InvocationRequest request = new DefaultInvocationRequest();
//指定pom文件代码
request.setPomFile(new File("D:\\xx\\research-demo\\pom.xml"));
//指定maven命令
request.setGoals(Collections.singletonList("clean install compile"));
Invoker invoker = new DefaultInvoker();
//指定安装目录
invoker.setMavenHome(new File("D:/App/apache-maven-3.6.3"));
invoker.setLogger(new PrintStreamLogger(System.err, InvokerLogger.ERROR) {
});
//用于打印信息
invoker.setOutputHandler(new InvocationOutputHandler() {
@Override
public void consumeLine(String s) throws IOException {
System.out.println(s);
}
});
try {
invoker.execute(request);
} catch (MavenInvocationException e) {
e.printStackTrace();
}
try {
if (invoker.execute(request).getExitCode() == 0) {
System.out.println("success");
} else {
System.err.println("error");
}
} catch (MavenInvocationException e) {
e.printStackTrace();
}
}
2.Maven embedder
引入相关依赖
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-embedder</artifactId>
<version>3.6.3</version>
</dependency>
<!-- 引入maven-compat,否则在调用内嵌的maven时,会出现错误
No implementation for org.apache.maven.repository.RepositorySystem was bound-->
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-compat</artifactId>
<version>3.6.3</version>
</dependency>
<!-- 这两个包用于deploy 未测试 -->
<dependency>
<groupId>org.apache.maven.resolver</groupId>
<artifactId>maven-resolver-connector-basic</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.resolver</groupId>
<artifactId>maven-resolver-transport-http</artifactId>
<version>1.4.1</version>
</dependency>
编写测试代码
public static void Main(String[] args) {
MavenCli mavenCli = new MavenCli();
// 设置多模块项目目录
System.setProperty("maven.multiModuleProjectDirectory", "D:\\xx\\test-demo");
// 若未设置环境变量,可在此显式指定
//System.setProperty("maven.home", "D:\\App\\apache-maven-3.6.3");
// 方式一 显式指定pom.xml,可以
String[] commandLineArgs = { "-f", "D:\\hearken-das-workplace\\test-demo\\pom.xml", "clean", "install" };
int result = mavenCli.doMain(commandLineArgs,
System.getProperty("maven.multiModuleProjectDirectory"),
System.out, System.err);
// 方式2 不显式指定,其会根据工作空间目录寻找pom.xml
//int result = mavenCli.doMain(new String[] { "clean", "install" },System.getProperty("maven.multiModuleProjectDirectory"),System.out, System.err);
if (result == 0) {
System.out.println("构建成功。");
} else {
System.out.println("构建失败。");
}
}