目录
不设置MavenHome
pom依赖引入
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>2.2</version>
</dependency>
编写例子
package com.colde.dexster.util;
import org.apache.maven.shared.invoker.*;
import java.io.File;
import java.util.Collections;
/**
* @description:
* @create: 2021/4/28 下午3:49
*/
public class MavenInvokerDemo {
public static void main(String[] args) {
InvocationRequest request = new DefaultInvocationRequest();
String relativelyPath=System.getProperty("user.dir");
String pomPath = relativelyPath+"/pom.xml";
System.out.println(pomPath);
request.setPomFile(new File(pomPath));
request.setGoals(Collections.singletonList("package"));
Invoker invoker = new DefaultInvoker();
try {
invoker.execute(request);
} catch (MavenInvocationException e) {
e.printStackTrace();
}
}
}
设置MavenHome
配置maven环境变量
编写例子程序
package com.colde.dexster.util;
import org.apache.maven.shared.invoker.*;
import java.io.File;
import java.util.Collections;
/**
* @description:
* @create: 2021/4/28 下午3:49
*/
public class MavenInvokerDemo {
public static void main(String[] args) {
InvocationRequest request = new DefaultInvocationRequest();
String relativelyPath=System.getProperty("user.dir");
String pomPath = relativelyPath+"/pom.xml";
System.out.println(pomPath);
request.setPomFile(new File(pomPath));
request.setGoals(Collections.singletonList("package"));
Invoker invoker = new DefaultInvoker();
String m2Path = System.getenv("M2_HOME");
System.out.println("m2Path:"+m2Path);
invoker.setMavenHome(new File(m2Path));
try {
invoker.execute(request);
} catch (MavenInvocationException e) {
e.printStackTrace();
}
}
}
结果
如果首次编写的时候报错,可以尝试设置maven环境变量;因为第一次构建需要下载依赖,好像是之前下载好了,后面我去除了maven环境变量的设置也可以运行。