How to create a Java project with Maven

In this tutorial, we will show you how to use create a Java project with Maven, imports it into the Eclipse IDE, and package the Java project into a jar file.

Tools used :

  1. Maven 3.0.5
  2. Eclipse 4.2
  3. JDK 6
Note
Please make sure Maven is installed and configured properly (Windows, *nix, Mac OSX) before you proceed with this tutorial, to avoid mvn command not found error.

1. Create a Project from Maven Template

In a terminal (*uix or Mac) or command prompt (Windows), navigate to the folder you want to create the Java project. Type this command :

mvn archetype:generate -DgroupId={project-packaging} 
   -DartifactId={project-name} 
   -DarchetypeArtifactId=maven-archetype-quickstart 
   -DinteractiveMode=false

This tells Maven to create a Java project from the Maven maven-archetype-quickstarttemplate. If you ignore the archetypeArtifactId option, a huge list of the Maven templates will be listed.

For example,

$ mvn archetype:generate -DgroupId=com.mkyong -DartifactId=NumberGenerator 
	-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
 
[INFO] Scanning for projects...
 
[INFO] -- omitted for readability
 
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.mkyong
[INFO] Parameter: packageName, Value: com.mkyong
[INFO] Parameter: package, Value: com.mkyong
[INFO] Parameter: artifactId, Value: NumberGenerator
[INFO] Parameter: basedir, Value: /Users/mkyong/Documents/workspace
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: /Users/mkyong/Documents/workspace/NumberGenerator
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.917s
[INFO] Finished at: Mon Dec 17 18:53:58 MYT 2012
[INFO] Final Memory: 9M/24M
[INFO] ------------------------------------------------------------------------

In above case, a new Java project named “NumberGenerator”, and the entire project directory structure is created automatically.

Note
Few users commented below, the mvn archetype:generate command is failing to generate the project structure. Hmm…, sorry, I just can’t simulate it, if you have any similar issue, no worry, just skip this step, and create the folders manually, see step 2 project structure.

2. Maven Directory Layout

With mvn archetype:generate + maven-archetype-quickstart template, the following project directory structure is created.

NumberGenerator
   |-src
   |---main
   |-----java
   |-------com
   |---------mkyong
   |-----------App.java
   |---test
   |-----java
   |-------com
   |---------mkyong
   |-----------AppTest.java
   |-pom.xml

In simple, all source code puts in folder /src/main/java/, all unit test code puts in /src/test/java/.

In additional, a standard pom.xml is generated. This POM file is like the Ant build.xml file, it describes the entire project information, everything from directory structure, project plugins, project dependencies, how to build this project and etc, read this official POM guide.

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.mkyong</groupId>
  <artifactId>NumberGenerator</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>NumberGenerator</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>

3. Eclipse IDE

To make this as an Eclipse project, in terminal, navigate to “NumberGenerator” project, type this command :

mvn eclipse:eclipse

It will generate all project files that are required by Eclipse IDE.

Figure : Project is imported it into Eclipse IDE

project directory

To import the project into Eclipse IDE, select “File -> Import… -> General->Existing Projects into Workspace”

4. Update POM

The default pom.xml is too simple, often times you need to add the compiler plugin to tell Maven which JDK version is used to compile your project. (The default JDK1.4 is too old).

	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>2.3.2</version>
		<configuration>
			<source>1.6</source>
			<target>1.6</target>
		</configuration>
	</plugin>

Update the jUnit from 3.8.1 to latest 4.11.

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.11</version>
		<scope>test</scope>
	</dependency>
Maven Coordinate
The above XML code snippet is called “Maven Coordinate”, If you want junit jar, you need to find out its corresponding Maven coordinate. It applied to all other dependencies, such as Spring, Hibernate, Apache common and etc, just go Maven center repository and find out what is the correct Maven coordinate of the dependency.
pom.xml – updated version
<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.mkyong</groupId>
	<artifactId>NumberGenerator</artifactId>
	<packaging>jar</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>NumberGenerator</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
 
	<build>
	  <plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
			<configuration>
				<source>1.6</source>
				<target>1.6</target>
			</configuration>
		</plugin>
	  </plugins>
	</build>
 
</project>

In terminal, issue the same command mvn eclipse:eclipse again, Maven will download the plugins and project dependencies (junit) from Maven center repository and store it into your local Maven repository automatically.

5. Update Business Logic

Test driven development (TDD), update the unit test first, to make sure App object has a method to generate a unique key that contains exactly 36 alphabets.

AppTest.java
package com.mkyong;
 
import org.junit.Assert;
import org.junit.Test;
 
public class AppTest {
 
	@Test
	public void testLengthOfTheUniqueKey() {
 
		App obj = new App();
		Assert.assertEquals(36, obj.generateUniqueKey().length());
 
	}
}

Complete the business logic.

App.java
package com.mkyong;
 
import java.util.UUID;
 
/**
 * Generate a unique number
 *
 */
public class App 
{
 
    public static void main( String[] args )
    {
        App obj = new App();
        System.out.println("Unique ID : " + obj.generateUniqueKey());
    }
 
    public String generateUniqueKey(){
 
    	String id = UUID.randomUUID().toString();
    	return id;
 
    }
}

6. Maven Packaging

Now, we will use Maven to compile this project and output to a “jar” file. Refer to the pom.xml file, the packaging element defined what should be the packaging output.

pom.xml
<project ...>
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong</groupId>
	<artifactId>NumberGenerator</artifactId>
 
	<packaging>jar</packaging>
 
	<version>1.0-SNAPSHOT</version>
	<!--

In terminal, type mvn package :

$pwd
/Users/mkyong/Documents/workspace/NumberGenerator
 
$ mvn package
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building NumberGenerator 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ...omitted for readability
 
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.mkyong.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.078 sec
 
Results :
 
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
 
[INFO] 
[INFO] --- maven-jar-plugin:2.3.1:jar (default-jar) @ NumberGenerator ---
[INFO] Building jar: /Users/mkyong/Documents/workspace/NumberGenerator/target/NumberGenerator-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.064s
[INFO] Finished at: Mon Dec 17 23:38:05 MYT 2012
[INFO] Final Memory: 15M/135M
[INFO] ------------------------------------------------------------------------

It compiles, run unit test and package the project into a jar file and put it in the project/target folder.

Figure : Final project directory structure.

final project directory

7. Demo

Run the App example from the project jar file ~

$pwd
/Users/mkyong/Documents/workspace/NumberGenerator
 
$ java -cp target/NumberGenerator-1.0-SNAPSHOT.jar com.mkyong.App
Unique ID : f1947107-2deb-4926-a635-ea3db61453e8
 
$ java -cp target/NumberGenerator-1.0-SNAPSHOT.jar com.mkyong.App
Unique ID : 98ed9e1c-d1bc-47f1-847d-64db451ce0ff
How about project’s dependencies?
Read these articles – Maven fat jar example (one-jar), Maven fat jar example (shade plugin) and Maven thin jar example.

Download Source Code

Download it – Maven-NumberGenerator.zip (12 KB)

References

  1. Apache Maven Project
  2. A Simple Maven Project
  3. How To Create a Jar File, thin-jar example
  4. Create a fat Jar file – One-JAR example
  5. Create a fat Jar file – Maven Shade Plugin example
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: Deb's Desk – Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)()

  • Pingback: Maven command line | indybee83()

  • ahmed abbas

    thanks so much.

    first time to practice with maven. nice tutrial

  • hi

    hi,
    this is the error i am getting plss help

    Downloading: http://10.132.96.226:9090/archiva/repository/internal/org/apache/ma
    ven/plugins/maven-metadata.xml
    Downloading: http://10.132.96.226:9090/archiva/repository/internal/org/codehaus/
    mojo/maven-metadata.xml
    [WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xm
    l from/to archiva.default (http://10.132.96.226:9090/archiva/repository/internal
    /): Error transferring file: Server returned HTTP response code: 502 for URL: ht
    tp://10.132.96.226:9090/archiva/repository/internal/org/apache/maven/plugins/mav
    en-metadata.xml
    [WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from/
    to archiva.default (http://10.132.96.226:9090/archiva/repository/internal/): Err
    or transferring file: Server returned HTTP response code: 502 for URL: http://10
    .132.96.226:9090/archiva/repository/internal/org/codehaus/mojo/maven-metadata.xm
    l
    [INFO] ————————————————————————
    [INFO] BUILD FAILURE
    [INFO] ————————————————————————
    [INFO] Total time: 1:59.247s
    [INFO] Finished at: Wed Oct 23 16:41:07 IST 2013
    [INFO] Final Memory: 4M/15M
    [INFO] ————————————————————————
    [ERROR] No plugin found for prefix ‘archetype’ in the current project and in the
    plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
    repositories [local (E:\apache-maven-3.0.3\maven_repo), archiva.default (http://
    10.132.96.226:9090/archiva/repository/internal/)] -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
    ch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please rea
    d the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundF
    orPrefixException

  • Zenith

    Best one for a beginner :)

  • Pingback: Maven — ?????? 1 ??????????? Java ???? Maven | Tumit's Blog()

  • Kedar

    Excellent!!!

    Works like butter…..I was not much knowing about Maven, but this gave me some confidence.

  • http://javabyab.com Milad

    Hi !
    ” 1. Create a Project from Maven Template ”
    I can not create a project . when I write code in cmd ( windows ) it’s Error .
    please help to creat a project and run apache syncope .
    TnQ

    • http://[email protected] Yilin

      Have you downloaded Maven (http://maven.apache.org/download.cgi) and set to your environment variable? if not, no cmd knows what mvn is.

  • http://[email protected] sushmita

    hi,

    Iam getting build error while creating the project:Property artifactID is missing,Can anyone let me know where to configure artifactID.

    • http://bitexodus.com Enrique

      Take a look at your “pom.xml” file. One of the elements is the “artifactId” node.

  • mKay

    Hi, I’m struggling to figure out how to actually import the library that I got through maven. Any suggestions how I can find out the name or path to the library that I got from maven?

    For some reason I’m not able to figure out how to import the library into my class… :(

  • Daniel

    Hi There..

    I have a machine i can not connect to the internet, and getting the error:
    ERROR] No plugin found for prefix ?archetype? in the current project and in the
    plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
    repositories [local (C:\Documents and Settings\paris\.m2\repository), centra
    l (http://repo1.maven.org/maven2)] -> [Help 1]

    is there a way around this? can i download it? where? how? etc.

    Many thanks in advance! :)
    Daniel

  • Ivan

    Very good tutorial. Thanks bro’!!

  • Awanth

    I have builts the maven archetype project and it builds successfully, but when i open the project in eclipse it shows errors int he api and omod projects.. any idea how to solve those?
    thanks

  • satyam

    The complete explanation was great and I triggered successfully my application in one shot by looking this content.

    Great work mkyong!

  • Ram Srinivasan

    Works very nicely. I made it work with Java 1.7 on an AWS EC2. Thank you for a step by step example. Clear instructions.

  • http://bitexodus.com Enrique

    Very good tutorial. I just miss something about the properties, one of them very important to create platform independent builds: “project.build.sourceEncoding”.

    Good work and good website.

  • Alice

    I am getting the same error as Paris :
    [ERROR] No plugin found for prefix ‘archetype’ in the current project and in the
    plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
    repositories [local (C:\Documents and Settings\paris\.m2\repository), centra
    l (http://repo1.maven.org/maven2)] -> [Help 1]

    Please let me know a solution. I am trying to create a maven proj in Win 8. Many thanks!

    • galindo

      Even it’s late, it could be useful for another person ;)

      Check if you are behind a proxy, if so try to configure the proxy in the file settings.xml under Maven install folder :

      someproxyid
      true
      http


      myproxyhostname
      8080
      localhost|127.0.0.1

  • Rama Viswanath

    Excellent tutorial !!!!
    thanks a lot

  • tumit

    Very very thx, your very clear tutorial make me to easy :)

  • g00glen00b

    And this is why I like m2e/m2eclipse so much… you can execute all these commands by following some wizards.
    That doesn’t change the fact that this is another great tutorial.

  • haris

    when I gave command :
    mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mkyong-core
    -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

    i got following steps(in ubuntu) please help.. wht do i have to do after this steps …??

    670: remote -> org.zkoss:zk-archetype-component (The ZK Component archetype)
    671: remote -> org.zkoss:zk-archetype-webapp (The ZK wepapp archetype)
    672: remote -> ru.circumflex:circumflex-archetype (-)
    673: remote -> se.vgregion.javg.maven.archetypes:javg-minimal-archetype (-)
    674: remote -> sk.seges.sesam:sesam-annotation-archetype (-)
    675: remote -> tk.skuro:clojure-maven-archetype (A simple Maven archetype for Clojure)
    676: remote -> uk.ac.rdg.resc:edal-ncwms-based-webapp (-)
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 228: Choose archetype:
    Your filter doesn’t match any archetype (hint: enter to return to initial list)
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 228
    Choose archetype:
    Your filter doesn’t match any archetype (hint: enter to return to initial list)
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : mkyong-core
    Choose archetype:
    Your filter doesn’t match any archetype (hint: enter to return to initial list)
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains):

  • http://emrpms.blogspot.in/ Senthil Muthiah

    Hi mkYong,

    You are doing a good job. I have some basic question

    1. What is the difference between maved based java project and maven based web application project.

    2. Your tutorial http://www.mkyong.com/spring-security/spring-security-hello-world-example/ is a maven based java project or maven based web application project.

    Regards
    Senthil

  • Pablo

    Hi!! What maven archetype number should I use if I want to create a project with JSF, Spring, Hibernate, MySQL?

    If you have or know of a tutorial that can help me, can you please redirect me?

  • Karthik

    Im getting the below error, Please help me,
    D:\MavenWorkspace>mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mkyong-core -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
    [INFO] Scanning for projects…
    [INFO] Searching repository for plugin with prefix: ‘archetype’.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [WARNING] repository metadata for: ‘org.apache.maven.plugins’ could not be retrieved from repository: central due to an error: Error transferring file: Connection timed out: connect
    [INFO] Repository ‘central’ will be blacklisted
    [INFO] ————————————————————————
    [ERROR] BUILD ERROR
    [INFO] ————————————————————————
    [INFO] The plugin ‘org.apache.maven.plugins:maven-archetype-plugin’ does not exist or no valid version could be found
    [INFO] ————————————————————————
    [INFO] For more information, run Maven with the -e switch
    [INFO] ————————————————————————
    [INFO] Total time: 21 seconds
    [INFO] Finished at: Thu Aug 02 15:48:42 GMT+05:30 2012
    [INFO] Final Memory: 1M/4M
    [INFO] ————————————————————————

  • tausif

    mkYong,

    You’re a genius. My sincere gratitude for sharing this knowledge with us.

    Kind Regards and Thanks.

  • Paris

    I AM GETTING THIS ERROR WHILE CREATING JAVA PROJECT WITH MAVEN.
    PLEASE ANYONE HELP ME OUT!!!

    [ERROR] No plugin found for prefix ‘archetype’ in the current project and in the
    plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
    repositories [local (C:\Documents and Settings\paris\.m2\repository), centra
    l (http://repo1.maven.org/maven2)] -> [Help 1]
    [ERROR]

    • http://www.mkyong.com mkyong

      Above script was tested in Maven2, and now i used Maven3 to test it, it’s working fine also. Mind to guide me to simulate your error?

    • Jenny

      If you didn’t change the proxies setting in your Maven settings.xml, your machine could be behind a firewall or proxy so you can’t reach http://repo1.maven.org/maven2.
      To test: hit this URL directly in a browser, and see if you are able to make the request.

  • Pingback: Java + MongoDB hello world example()

  • Pingback: Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)()

  • Pingback: How to create a Web Application Project with Maven()

  • Pingback: How to convert Maven Java Project to support Eclipse IDE()