Build Simple Java Project with Maven

In this article, we will create a very simple java project and build it with Maven. This guide will help you to understand the basics of Java coding and how to build this code with Maven.

Create a Github Repository:

I hope you have Github repository, if not I recommend you to create one. To download and use it with other projects I will add this code to my Github repository.

Create a repository called “sample-java-project” on Github.

 

Clone the empty repository to your terminal.

$ git clone https://github.com/techiescorner/sample-maven-project.git

Cloning into 'sample-maven-project'...

warning: You appear to have cloned an empty repository.

Git installation and configuration are not a scope of this tutorial so skipped that.

 

Create a folder structure:

Here I am using the nix (Amazon Linux ) system to do the coding.

Create a directory structure as follows inside the repository folder

$ cd sample-maven-project/
.

└── src

    └── main

        └── java

            └── first

Execute the below command to create the directory.

mkdir -p src/main/java/first

Next, create two classes inside the “first” folder. I have created FirstCode.java and Welcome.java you can create any java classes.

Open the FirstCode.java file with your favorite editor and add the below code.

package hello;

public class FirstCode {
    public static void main(String[] args) {
        Welcome greeter = new Greeter();
        System.out.println(greeter.sayHello());
    }
}

Next, Open the Welcome.java file and add the below code.

package hello;

public class Welcome {

    public String sayHello() {

        return "Welcome to the first Java code !!!!";

    }

}

Now the code is ready, next, we have to build it with Maven. I have already installed Maven in the system. If you haven’t installed please refer below link.

Maven installation.

Create a Maven pom.xml file

Once the maven is installed we have to create a pom.xml file. POM.xml file is a Maven project definition. This file contains the details like Project name, version, and dependencies. Create this file near the “src” folder.

create a file named pom.xml file and add the below codes.

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>www.techiescorner.in</groupId>
    <artifactId>TC-Maven</artifactId>
    <packaging>jar</packaging>
    <version>0.1.0</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>hello.FirstCode</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project> 

The above pom.xml file is the simplest one for a project and it contains the following details.

<modelVersion> : POM model version.

<groupId> : Organization or Group name which the project belongs to.

<artificatId> :  Name for the project’s library artifact (for example, the name of its JAR or WAR file)

<version> : Version of the project

<packaging> : How the project output should be packaged. Defaults to “jar” for JAR file                                           packaging. Use “war” for WAR file packaging.

<mainClass> : Add your mail class name here.

Build the java code:

We have developed our code and now it is ready to build using Maven. To compile the code execute below command from where pom.xml file is present.

[root@jenkins ~]# mvn compile

[INFO] Scanning for projects...

[INFO] 

[INFO] -------------------< www.techiescorner.in:TC-maven >--------------------

[INFO] Building TC-maven 0.1.0

[INFO] --------------------------------[ jar ]---------------------------------

[INFO] 

[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ TC-maven ---

[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory /root/src/main/resources

[INFO] 

[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ TC-maven ---

[INFO] Changes detected - recompiling the module!

[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!

[INFO] Compiling 2 source files to /root/target/classes

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESS

If you are executing it the first time it may take a few minutes to complete the compile.

The compiled .class files will be in the target/classes directory.

Next, we have to package the compiled code. The package command will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory.

Execute the below command to package the compiled code from the same folder.

# ls
pom.xml  src  target
[root@jenkins ~]# mvn package
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------< www.techiescorner.in:TC-maven >--------------------
[INFO] Building TC-maven 0.1.0
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ TC-maven 
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ TC-maven ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ TC-maven ---
[INFO] Building jar: /root/target/TC-maven-0.1.0.jar
[INFO] 
[INFO] --- maven-shade-plugin:2.1:shade (default) @ TC-maven ---
[INFO] Replacing original artifact with shaded artifact.
[INFO] Replacing /root/target/TC-maven-0.1.0.jar with /root/target/TC-maven-0.1.0-shaded.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS

Once the build is completed you will get a success message at the end.

The name of the output JAR file will be based on the project’s <artifactId> and <version> and present in the target folder.

]# ls
classes  generated-sources  maven-archiver  maven-status   TC-maven-0.1.0.jar

To get the output of the code or to open the JAR execute below command from the target folder.

# java -jar TC-maven-0.1.0.jar 

Welcome to the first Java code !!!!

We have successfully built our Java code.

 

Push the code to Github:

Execute the below codes from the sample-maven-project directory to push the code to the Github repository.

[root@jenkins sample-maven-project]# git init
Initialized empty Git repository in /root/sample-maven-project/.git/

[root@jenkins sample-maven-project]# ls
pom.xml  src  target

[root@jenkins sample-maven-project]# git add .
[root@jenkins sample-maven-project]# git commit -m "sample java code"
[master (root-commit) c2997f4] sample java code
 9 files changed, 64 insertions(+)
 create mode 100644 pom.xml
 create mode 100644 src/main/java/first/FirstCode.java
 create mode 100644 src/main/java/first/Welcome.java
 create mode 100644 target/TC-maven-0.1.0.jar
 create mode 100644 target/classes/hello/FirstCode.class
 create mode 100644 target/classes/hello/Welcome.class
 create mode 100644 target/maven-archiver/pom.properties
create mode 100644 target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst
create mode 100644 target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

# git remote add origin https://github.com/techiescorner/sample-maven-project.git

# git remote -v
origin https://github.com/techiescorner/sample-maven-project.git (fetch)
origin https://github.com/techiescorner/sample-maven-project.git (push)

# git push -u origin master
Username for 'https://github.com': techiescorner
Password for 'https://techiescorner@github.com': 
Counting objects: 23, done.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (23/23), 4.47 KiB | 2.23 MiB/s, done.
Total 23 (delta 0), reused 0 (delta 0)
To https://github.com/techiescorner/sample-maven-project.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

To download the code to your server or local machine execute the below code.

git clone https://github.com/techiescorner/sample-maven-project.git

 

Leave a Reply

Your email address will not be published. Required fields are marked *