Saturday, November 22, 2014

Maven: add plugin to pom configuration for Maven to compile and execute a Maven java project.

This post shows how to add xml plugin section into the pom.xml file for a maven project, so that the result can be compiled and executed. Create a Maven project using Eclipse or STS with groupId = "com.trying" and artifactId = "hello-world" (these are just made-up names so that a hello-world project will be generated with namespace com.trying.hello_world). Let's say the project has a main class com.trying.hello_world.App, which contains the main() method, that looks like the following

public static void main(String[] args)
{
   System.out.println("Hello World");
}

Now open the pom.xml file created in the project and add the following section to the end:

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>

<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>

<configuration>
<executable>java</executable>
<includeProjectDependencies>true</includeProjectDependencies>
<includePluginDependencies>false</includePluginDependencies>
<classpathScope>exec</classpathScope>
<mainClass>com.trying.hello_world.App</mainClass>
</configuration>
</plugin>
</plugins>
</build>

Save and close pom.xml. Now navigate the project root folder, then compile and execute the program in the terminal:

> cd $PROJECT_HOME/hello-world
> mvn compile exec:java

You should see the output "Hello World" as well as messages indicating the project is built successfully (the output classes are in the hello-world/target sub folder).

No comments:

Post a Comment