问题
I want to know if it's possible to run the maven command: archetype:generate in Java code. I've tried this with the maven embedder, but this library is deprecated.
I want to do an archetype:generate from a remote catalog, and capture the required properties of the archetype.
The maven command I want to run is for example:
mvn archetype:generate \
-DgroupId=com.maven \
-DartifactId=test \
-DarchetypeVersion=1.0-alpha-4 \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-j2ee-simple \
-DinteractiveMode=false \
-DarchetypeCatalog=http://repo1.maven.org/maven2/archetype-catalog.xml
for some archetypes there are required properties, after you do this request. I want to display these properties on a GUI screen, just like the m2eclipse plugin does, so the user can fill in these properties.
Does anybody has a suggestion?
回答1:
You could try to use the Maven Invoker.
Add this dependency to the pom.xml
:
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>2.1.1</version>
</dependency>
And here is what the code might look like:
import org.apache.maven.shared.invoker.*;
import java.util.Collections;
import java.util.Properties;
public class MavenInvoker {
public static void main(String[] args) throws MavenInvocationException {
InvocationRequest request = new DefaultInvocationRequest();
request.setGoals( Collections.singletonList("archetype:generate") );
request.setInteractive(false);
Properties properties = new Properties();
properties.setProperty("groupId", "com.maven");
properties.setProperty("artifactId", "test");
properties.setProperty("archetypeVersion", "1.0-alpha-4");
properties.setProperty("archetypeGroupId", "org.apache.maven.archetypes");
properties.setProperty("archetypeArtifactId", "maven-archetype-j2ee-simple");
properties.setProperty("archetypeCatalog", "http://repo1.maven.org/maven2/archetype-catalog.xml");
request.setProperties(properties);
Invoker invoker = new DefaultInvoker();
InvocationResult result = invoker.execute( request );
}
}
回答2:
If all else fails, you can use Runtime.exec().
来源:https://stackoverflow.com/questions/16541124/generate-maven-archetype-from-java-code