有什么办法可以使用Maven API将Maven项目打包到jar中?

时间:2018-08-08 07:15:02

标签: java maven

假设我在In [44]: pd.concat([df.astype(float), series]) 中有一个maven项目,则可以使用以下命令将该项目打包到jar中。

<servlet>
  <servlet-name>TheServlet</servlet-name>
  <servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
  <init-param>
    <param-name>org.restlet.component</param-name>
    <param-value>RestletComponent</param-value>
  </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>TheServlet</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

现在我想使用Java和相关的maven-api进行操作,是否有类似的东西?

/home/admin/projects/maven-sample-project

1 个答案:

答案 0 :(得分:0)

正如khmarbaise所提到的,maven-invoker能够解决此问题。

首先在您的pom.xml文件中添加依赖项。

<dependency>
    <groupId>org.apache.maven.shared</groupId>
    <artifactId>maven-invoker</artifactId>
    <version>3.0.1</version>
</dependency>

然后创建一个新类。

import org.apache.maven.shared.invoker.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MavenRunner {

    public static final String MAVEN_COMMAND_CLEAN = "clean";
    public static final String MAVEN_COMMAND_PACKAGE = "package";

    public static void run(String mavenProjectLocation, List<String> goals) throws MavenInvocationException {
        Invoker invoker = getInvoker(mavenProjectLocation);
        InvocationRequest request = getInvocationRequest(mavenProjectLocation, goals);
        InvocationResult result = invoker.execute(request);
        if ( result.getExitCode() != 0 )
        {
            String exceptionMsgPrefix = String.format("Failed to run maven commands, mavenProjectLocation: %s, goals: %s.", mavenProjectLocation, goals);
            if ( result.getExecutionException() != null )
            {
                throw new MavenInvocationException(exceptionMsgPrefix + "exception: " + result.getExecutionException());
            }
            else
            {
                throw new MavenInvocationException(exceptionMsgPrefix + "exit code: " + result.getExitCode());
            }
        }
    }
    private static Invoker getInvoker(String mavenProjectLocation) {
        Invoker invoker = new DefaultInvoker();
        invoker.setLocalRepositoryDirectory(new File(mavenProjectLocation));
        // replace it with yours
        invoker.setMavenHome(new File("/home/admin/apps/apache-maven-3.5.2"));
        return invoker;
    }
    private static InvocationRequest getInvocationRequest(String mavenProjectLocation, List<String> goals) {
        InvocationRequest request = new DefaultInvocationRequest();
        request.setBaseDirectory(new File(mavenProjectLocation));
        request.setGoals(goals);
        return request;
    }
}

用法:

String mavenProjectLocation = "/home/admin/projects/maven-sample-project";
List<String> goals = Arrays.asList(MavenRunner.MAVEN_COMMAND_CLEAN, MavenRunner.MAVEN_COMMAND_PACKAGE);
MavenRunner.run(mavenProjectLocation, goals);
相关问题