How to run maven from java?

2020-01-23 07:34发布

I want to execute maven command from Java for development of a plugin. I tried maven-embedder but looks like it is now not supported. Is someone aware of some other tool which can be used?

3条回答
The star\"
2楼-- · 2020-01-23 07:48

Maven embedder is indeed no longer supported (only hudson still uses it). But, as in hudson, there are several other ways to run maven. You could simply run maven as an external program:

Runtime.getRuntime().exec("mvn clean install");

Or you could consider creating an ant script for maven. This script could then be called either as an external program or (if you need more control) adding ant to your classpath and calling the Antrunner.

UPDATE

Maven embedder is now supported again so that is your best option.

查看更多
趁早两清
3楼-- · 2020-01-23 08:00

Use Maven Embedder

Maven embedder is still supported and easy to configure, so this is better option for you.

Java code

MavenCli cli = new MavenCli();
cli.doMain(new String[]{"clean", "install"}, "project_dir", System.out, System.out);

Project configuration

<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>

Fully working example: https://github.com/mariuszs/maven-cli-example

查看更多
Explosion°爆炸
4楼-- · 2020-01-23 08:02

A simple invocation API : maven-invoker.

Project documentation : http://maven.apache.org/shared/maven-invoker/

Usage : http://maven.apache.org/shared/maven-invoker/usage.html

InvocationRequest request = new DefaultInvocationRequest();
request.setPomFile( new File( "/path/to/pom.xml" ) );
request.setGoals( Arrays.asList( "clean", "install" ) );

Invoker invoker = new DefaultInvoker();
invoker.execute( request );
查看更多
登录 后发表回答