Create a Maven Project with CommandLine

In this tutorial, we will look on how to create a java project with Maven.


Following technologies being used:

  • Maven 3.1.1
  • JDK 1.6
  • Eclipse JUNO Service Release 2
  • M2Eclipse plugin (Optional)

Let’s get going.

Step 1: Install and setup maven

In case you don’t have maven already installed on your system, Please follow Maven Download & Installation containing step-by-step instruction to setup maven.

Step 2: Use Maven template to generate project structure and artifacts

Following is the syntax of maven template:

mvn archetype:generate -DgroupId=YourProjectGroupId -DartifactId=YourProjectName -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Description :

  • groupId : Refers to project packaging and identifies your project uniquely across all projects.
  • artifactId : Name of jar of your project without version.
  • version : Version number of your choice.
  • archetypeArtifactId : Template type.Several templates are available to choose from.
  • interactiveMode : If set to true, maven will ask confirmation on each step of project generation.

Update above template with your project parameters.Open command prompt/terminal , navigate to your preferred directory you would like to create your project in and fire above command

$>mvn archetype:generate -DgroupId=com.websystique.maven -DartifactId=SampleMavenJavaProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

You will see following output

E:\workspace>mvn archetype:generate -DgroupId=com.websystique.maven -DartifactId=MavenSampleJavaProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>
>
[INFO]
[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<
<
[INFO]
[INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom --
-
[INFO] Generating project in Batch mode
[INFO] -------------------------------------------------------------------------
---
[INFO] Using following parameters for creating project from Old (1.x) Archetype:
 maven-archetype-quickstart:1.0
[INFO] -------------------------------------------------------------------------
---
[INFO] Parameter: groupId, Value: com.websystique.maven
[INFO] Parameter: packageName, Value: com.websystique.maven
[INFO] Parameter: package, Value: com.websystique.maven
[INFO] Parameter: artifactId, Value: MavenSampleJavaProject
[INFO] Parameter: basedir, Value: E:\workspace
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: E:\workspace\MavenSampleJavaProject
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.112s
[INFO] Finished at: Fri Jul 25 22:12:30 CEST 2014
[INFO] Final Memory: 11M/112M
[INFO] ------------<------------------------------------------------------------

Browse to generated project directory and you should see the following:

MavenSampleJavaProject_img1

Basically two different directories structure are generated along with maven pom.xml. All your source code of application should be in src/main/java & all unit-test code should be in src/test/java

File pom.xml contains the information and instructions for maven to do it’s job. You must update pom.xml with all the information your project will rely upon(dependencies, profiles,…).

Below is the default generated pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.websystique.maven</groupId>
  <artifactId>MavenSampleJavaProject</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>MavenSampleJavaProject</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Dependency section refers to the library your project is replying upon. These libraries are found on different maven repositories.

For instance, if your code will be using spring framework and your test cases relies upon TestNG instead of junit, your pom.xml will include the dependency for Spring and TestNG like below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.websystique.maven</groupId>
  <artifactId>MavenSampleJavaProject</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>MavenSampleJavaProject</name>
  <url>http://maven.apache.org</url>
    <properties>
        <springframework.version>4.0.5.RELEASE</springframework.version>
        <testng.version>6.8.8</testng.version>
        <assertion.version>1.4</assertion.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
        </dependency>
	    <dependency>
	    	<groupId>org.easytesting</groupId>
	      	<artifactId>fest-assert</artifactId>
	      	<version>${assertion.version}</version>
	    </dependency>
    </dependencies>
</project>

Please check Maven pom guide to learn more about pom.

Step 3: Convert generated Maven project to Eclipse compatible form.

Go back to command line/terminal , navigate to project root, and fire mvn eclipse:eclipse

E:\workspace\MavenSampleJavaProject>mvn eclipse:eclipse

You will see that maven downloads required resources/dependencies from maven repository.You will also note that maven have created a .class and .project file on project root.Thanks to these files, you can now import your project into Eclipse IDE.

Step 4: Import your project into Eclipse

Open Eclipse. Select File->Import->Maven->Existing Maven Projects->Next , Browse to your newly created project directory, click Finish.

From here on , you can use eclipse to manage your porject, edit pom.xml and enjoy other handy eclipse plugins like m2eclipse to quickly clean build or install your project.

For instance, let’s write a unit test and run with maven:

Create/update a class App.java in src/main/java (via eclipse) :

package com.websystique.maven;

public class App{ 

	public static void main( String[] args ){
        App app = new App();
        int addition = app.sum(10, 20);
    	System.out.println( "Addition : "+addition);
    }

    public int sum(int a, int b){
    	return a+b;
    }
}

Create/update a test class AppTest.java in src/main/java (via eclipse) :

package com.websystique.maven;

import static org.fest.assertions.Assertions.assertThat;

import org.testng.annotations.Test;
/**
 * Unit test for simple App.
 */
public class AppTest{ 

	App app = new App();

	@Test
	public void testSum(){
		int expected = 30;
		int actual = app.sum(10, 20);
		assertThat(actual).isEqualTo(expected);
	}

}

Note that here we are using TestNG framework to test our sample class.Now fire mvn clean install on command line/terminal.

E:\workspace\MavenSampleJavaProject>mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MavenSampleJavaProject 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ MavenSampleJavaProject
 ---
[INFO] Deleting E:\workspace\MavenSampleJavaProject\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MavenSampl
eJavaProject ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\MavenSampleJavaProject\
src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ MavenSampleJa
vaProject ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 1 source file to E:\workspace\MavenSampleJavaProject\target\cl
asses
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ Ma
venSampleJavaProject ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory E:\workspace\MavenSampleJavaProject\
src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ Maven
SampleJavaProject ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 1 source file to E:\workspace\MavenSampleJavaProject\target\te
st-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ MavenSampleJavaPro
ject ---
[INFO] Surefire report directory: E:\workspace\MavenSampleJavaProject\target\su
refire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.websystique.maven.AppTest
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configur
ator@59bca5f1
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.435 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ MavenSampleJavaProject ---
[INFO] Building jar: E:\workspace\MavenSampleJavaProject\target\MavenSampleJava
Project-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ MavenSampleJavaP
roject ---
[INFO] Installing E:\workspace\MavenSampleJavaProject\target\MavenSampleJavaPro
ject-1.0-SNAPSHOT.jar to C:\Users\puneet\.m2\repository\com\websystique\maven\Ma
venSampleJavaProject\1.0-SNAPSHOT\MavenSampleJavaProject-1.0-SNAPSHOT.jar
[INFO] Installing E:\workspace\MavenSampleJavaProject\pom.xml to C:\Users\punee
t\.m2\repository\com\websystique\maven\MavenSampleJavaProject\1.0-SNAPSHOT\Maven
SampleJavaProject-1.0-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.613s

You notice that test case was successfully run and passed. Refresh your eclipse to find that project output(MavenSampleJavaProject-1.0-SNAPSHOT.jar) is generated and visible under target folder.This jar is also available on your local M2 repository.

Let’s run our main program from this jar:

E:\workspace\MavenSampleJavaProject\target>java -classpath .;MavenSampleJavaProject-1.0-SNAPSHOT.jar com.websystique.maven.App
Addition : 30

That’s it

Download Source Code


References