Maven – How to create a Java project

In this tutorial, we will show you how to use Maven to manage a Java project – create, add dependencies and package a Java project into an executable jar file. At the end, we will create an executable jar file to hash a given string with the SHA-256 algorithm.

Technologies used :

  1. Maven 3.5.3
  2. JDK 8
  3. Apache Commons Codec 1.11

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-template} 
	-DinteractiveMode=false

This tells Maven to generate a Java project from a Maven template. For example,


D:\>mvn archetype:generate -DgroupId=com.mkyong.hashing -DartifactId=java-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.992 s
[INFO] Finished at: 2018-09-27T17:15:57+08:00
[INFO] ------------------------------------------------------------------------

Above command will generate a Java project from maven-archetype-quickstart template.

2. Maven Directory Layout

The following project directory structure will be created. In short, source code puts in folder /src/main/java/, unit test code puts in /src/test/java/.

P.S Above figure is captured from IntelliJ IDEA, just ignore those .idea folder.

3. POM file

Review the generated pom.xml. It’s quite empty, just a single jUnit dependency.

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.hashing</groupId>
    <artifactId>java-project3</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>java-project</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>

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.

4. Update POM

4.1 Add compiler properties to tell Maven use a specified JDK version to compile the source code.


	<properties>
		<!-- https://maven.apache.org/general.html#encoding-warning -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

4.2 Update jUnit to 4.12


	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>

4.3 Add commons-codec for SHA hashing.


	<!-- Dependency for hashing -->
	<!-- https://search.maven.org/artifact/commons-codec/commons-codec/1.11/jar -->
	<dependency>
		<groupId>commons-codec</groupId>
		<artifactId>commons-codec</artifactId>
		<version>1.11</version>
	</dependency>

4.4 Complete updated version.

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.hashing</groupId>
    <artifactId>java-project</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>java-project</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- https://maven.apache.org/general.html#encoding-warning -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
    </dependencies>

</project>

5. Write Code

5.1 Update the App.java to accept an input and hash it with a SHA-256 algorithm.

App.java

package com.mkyong.hashing;

import org.apache.commons.codec.digest.DigestUtils;

public class App {

    public static void main(String[] args) {

        if (args.length < 1) {
            System.err.println("Please provide an input!");
            System.exit(0);
        }
        System.out.println(sha256hex(args[0]));

    }

    public static String sha256hex(String input) {
        return DigestUtils.sha256Hex(input);
    }

}

5.2 Unit Test.

AppTest.java

package com.mkyong.hashing;

import org.junit.Assert;
import org.junit.Test;

public class AppTest {

    private String INPUT = "123456";

    @Test
    public void testLength() {
        Assert.assertEquals(64, App.sha256hex(INPUT).length());
    }

    @Test
    public void testHex() {
        String expected = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
        Assert.assertEquals(expected, App.sha256hex(INPUT));
    }

}

Done.

6. Maven Build

6.1 Let build it with mvn package


D:\java-project>mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.mkyong.hashing:java-project >-------------------
[INFO] Building java-project 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
......

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.mkyong.hashing.AppTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.067 sec

Results :

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

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ java-project ---
[INFO] Building jar: D:\java-project\target\java-project-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.956 s
[INFO] Finished at: 2018-09-28T12:40:18+08:00
[INFO] ------------------------------------------------------------------------

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

7. Run#1

7.1 Run it. Oops… By default, Maven didn’t add the project dependencies commons-codec into the jar file.


D:\java-project>java -cp target/java-project-1.0-SNAPSHOT.jar com.mkyong.hashing.App 123456

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/codec/digest/DigestUtils
        at com.mkyong.hashing.App.sha256hex(App.java:18)
        at com.mkyong.hashing.App.main(App.java:13)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.digest.DigestUtils
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 2 more

7.2 To solve it, we can use this maven-shade-plugin to create an uber/fat-jar – group everything into a single jar file.

pom.xml

	<build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Attach the shade goal into the package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

7.3 Package it again!


D:\java-project>mvn clean package
[INFO] Scanning for projects...
[...

[INFO] --- maven-shade-plugin:3.2.0:shade (default) @ java-project ---
[INFO] Including commons-codec:commons-codec:jar:1.11 in the shaded jar.
[INFO] Replacing original artifact with shaded artifact.

[INFO] Replacing D:\java-project\target\java-project-1.0-SNAPSHOT.jar 
	with D:\java-project\target\java-project-1.0-SNAPSHOT-shaded.jar
...

Two jars will be generated, review the file size :


D:\java-project>dir target
 Volume in drive D is Samsung970
 Volume Serial Number is 10DF-E63D

 Directory of D:\java-project\target

28/09/2018  12:57 PM           335,643 java-project-1.0-SNAPSHOT.jar
28/09/2018  12:57 PM             3,053 original-java-project-1.0-SNAPSHOT.jar
...

8. Run#2

8.1 Run it again. Good, the result is expected.


D:\java-project>java -cp target/java-project-1.0-SNAPSHOT.jar com.mkyong.hashing.App 123456
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

8.2 Can we run it as Jar? No, there is no main class.


D:\java-project>java -jar target/java-project-1.0-SNAPSHOT.jar 123456
no main manifest attribute, in target/java-project-1.0-SNAPSHOT.jar

8.3 To solve it, add the main class in maven-shade-plugin like this.

pom.xml

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-shade-plugin</artifactId>
	<version>3.2.0</version>
	<executions>
		<!-- Attach the shade into the package phase -->
		<execution>
			<phase>package</phase>
			<goals>
				<goal>shade</goal>
			</goals>
			<configuration>
				<transformers>
					<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
						<mainClass>com.mkyong.hashing.App</mainClass>
					</transformer>
				</transformers>
			</configuration>
		</execution>
	</executions>
</plugin>

9. Run#3

9.1 Package it again!


D:\java-project>mvn clean package

9.2 Run it as Jar.


D:\java-project>java -jar target/java-project-1.0-SNAPSHOT.jar 123456
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

Done.

10. POM

Final POM file.

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.hashing</groupId>
    <artifactId>java-project</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>java-project</name>
    <url>http://maven.apache.org</url>

    <properties>
        <!-- https://maven.apache.org/general.html#encoding-warning -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.11</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Attach the shade into the package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.mkyong.hashing.App</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
			
        </plugins>
    </build>
</project>

Download Source Code

$ git clone https://github.com/mkyong/maven-examples.git
$ cd java-project
$ mvn package
$ java -jar target/java-project-1.0-SNAPSHOT.jar 123456

References

  1. Maven – How to create a Java web application project
  2. Apache Maven Project
  3. A Simple Maven Project
  4. Java SHA Hashing Example
  5. How To Create a Jar File, thin-jar example
  6. Create a fat Jar file – One-JAR example
  7. Create a fat Jar file – Maven Shade Plugin example
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
newest oldest most voted
martin
Guest
martin

Hi Mkyong.
Your tutorials are the best. Very well explained and simple, you go step by step.

Thank you very much!

Sathish G
Guest
Sathish G

hi mkyong,
i am following u r java articles for past 1 year .working first time with maven nice article

Lucy
Guest
Lucy

Nice tutorial by the way! May I ask how to convert Maven project into NetBeans IDE? I checked on other websites said that it could be automatically opened in NetBeans but I tried and failed to load the project in NetBeans. Anybody could help please? Thanks!!!

mkyong
Guest
mkyong

I don’t use Netbean, hope someone can answer this.

Jason.H
Guest
Jason.H

really nice ! tks !! Mkyong !

satyam
Guest
satyam

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

Great work mkyong!

trackback
How to convert Maven Java Project to support Eclipse IDE

[…] last tutorial, you created a Java project with Maven, but that project is not able to import into Eclipse IDE, because it is not Eclipse style […]

trackback
How to create a Web Application Project with Maven

[…] last tutorial, you created a Java Project with Maven. But that project is not a web application project, to create a web project with Maven, issue this […]

trackback
Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)

[…] 2. Create Project with Maven Use Maven to create a standard project structure. mvn archetype:generate -DgroupId=com.mkyong -DartifactId=HibernateExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false Note More detail, please refer to this How to create a Java project with Maven. […]

trackback
Java + MongoDB hello world example

[…] Create a Project Create a standard Java project, Maven is the fastest way to do it. mvn archetype:generate -DgroupId=com.mkyong.core […]

Paris
Guest
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]

Jenny
Guest
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.

tausif
Guest
tausif

mkYong,

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

Kind Regards and Thanks.

Karthik
Guest
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] ————————————————————————

Kausal Malladi
Guest
Kausal Malladi

Hi,
Even I got the same error. Please make sure you are connected to internet directly or update the proxy settings in settings.xml file. It should work!
This is for your reference..
http://maven.apache.org/guides/mini/guide-configuring-maven.html

Pablo
Guest
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?

Senthil Muthiah
Guest
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

haris
Guest
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… Read more »

mkyong
Guest
mkyong

No idea how to simulate this error, which Maven version you used? If the command is failing to generate the project structures, just ignore and create those folders manually.

Samrat
Guest
Samrat

Hi, this error has come for me on Window’s XP. If you use double quotes when running your command, it will work and create the directories as mentioned in the article. Hope this helps.

E.g.) E:E-BooksProjects>mvn archetype:generate “-DgroupId=com.user” “-DartifactId=
NumberGenerator” “-DarchetypeArtifactId=maven-archetype-quickstart” “-DinteractiveMode=false”

g00glen00b
Guest
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.

tumit
Guest
tumit

Very very thx, your very clear tutorial make me to easy πŸ™‚

Rama Viswanath
Guest
Rama Viswanath

Excellent tutorial !!!!
thanks a lot

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

Enrique
Guest
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.

Ram Srinivasan
Guest
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.

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

Ivan
Guest
Ivan

Very good tutorial. Thanks bro’!!

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

mkyong
Guest
mkyong

For the first time, Maven need internet to download those plugins and dependencies, unless you configure a local repository manager.

iSumanth
Guest
iSumanth

Sir , please tell me how to configure local repository manager ?

mKay
Guest
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… πŸ™

sushmita
Guest
sushmita

hi,

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

Enrique
Guest
Enrique

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

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

Yilin
Guest
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.

mkyong
Guest
mkyong

Make sure you installed and configured Maven properly. Set $MAVEN/bin to your environment.

Kedar
Guest
Kedar

Excellent!!!

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

trackback
Maven — ?????? 1 ??????????? Java ???? Maven | Tumit's Blog

[…] How to create a Java project with Maven– @mkyong […]

Zenith
Guest
Zenith

Best one for a beginner πŸ™‚