Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views23 pages

Devops 2

This document provides an overview of compiling and building Java projects using Maven and Gradle, detailing the Maven build lifecycle, goals, plugins, and dependency management. It explains the various phases of the Maven lifecycle, such as validate, compile, test, package, and deploy, along with the importance of build profiles and dependency management in multi-module projects. Additionally, it includes practical examples of Maven commands and how to manage dependencies in a project's pom.xml file.

Uploaded by

sandhyamca31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views23 pages

Devops 2

This document provides an overview of compiling and building Java projects using Maven and Gradle, detailing the Maven build lifecycle, goals, plugins, and dependency management. It explains the various phases of the Maven lifecycle, such as validate, compile, test, package, and deploy, along with the importance of build profiles and dependency management in multi-module projects. Additionally, it includes practical examples of Maven commands and how to manage dependencies in a project's pom.xml file.

Uploaded by

sandhyamca31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

lOMoARcPSD|15103529

CCS342 UNIT 2 - More

embedded system (Rajalakshmi Institute of Technology)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

UNIT-2 COMPILE & BUILD USING MAVEN AND GRADLE

Introduction, Installation of Maven, POM files, Maven Build lifecycle, build phases (compile
build, test, package) Maven Profiles, Maven repositories (local, central, global), Maven
plugins, Maven create and build Artificats, Dependency management, Installation of
Gradle, understand build using Gradle.

1. Maven Build Life Cycle


Maven is a powerful project management tool that is based on POM (project object
model), used for project build, dependency, and documentation. It is a tool that can be
used for building and managing any Java-based project. Maven makes the day-to-day
work of Java developers easier and helps with the building and running of any Java-based
project.

Maven Lifecycle: Below is a representation of the default Maven lifecycle and its 8 steps:
Validate, Compile, Test, Package, Integration test, Verify, Install, and Deploy.

Validate: This step validates if the project structure is correct. For example – It checks if
all the dependencies have been downloaded and are available in the local repository.
Compile: It compiles the source code, converts the .java files to .class, and stores the
classes in the target/classes folder.
Test: It runs unit tests for the project.
Package: This step packages the compiled code in a distributable format like JAR or WAR.
Integration test: It runs the integration tests for the project.
Verify: This step runs checks to verify that the project is valid and meets the quality
standards.
Install: This step installs the packaged code to the local Maven repository.
Deploy: It copies the packaged code to the remote repository for sharing it with other
developers.

Maven follows a sequential order to execute the commands where if you run step n, all
steps preceding it (Step 1 to n-1) are also executed. For example – if we run the
Installation step (Step 7), it will validate, compile, package and verify the project along
with running unit and integration tests (Step 1 to 6) before installing the built package to
the local repository.

In Maven, goals and plugins play a crucial role in executing specific tasks and extending
the functionality of the build process.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Maven Goals:
● Goals are specific tasks that Maven can perform during the build lifecycle.
● Each phase of the lifecycle is associated with one or more goals.
● Maven provides default goals for each phase, but you can also define custom goals.
● Goals can be executed from the command line using the mvn command followed
by the goal name.
● Examples of common Maven goals include compile, test, package, and install.
Maven Plugins:
● Plugins are the building blocks of Maven’s functionality.
● They provide implementations for various goals and can be used to extend the
build process.
● Maven has a vast ecosystem of plugins that cover a wide range of tasks and
integrations.
● Plugins can be configured in the project’s POM file, specifying the desired version
and any custom configurations.
● Maven resolves and downloads plugins from remote repositories when needed.
● Examples of popular Maven plugins include the Maven Compiler Plugin, Surefire
Plugin for testing, and the Maven Assembly Plugin for creating custom
distributions.
Maven Commands:
mvn clean: Cleans the project and removes all files generated by the previous build.
mvn compile: Compiles source code of the project.
mvn test-compile: Compiles the test source code.
mvn test: Runs tests for the project.
mvn package: Creates JAR or WAR file for the project to convert it into a distributable
format.
mvn install: Deploys the packaged JAR/ WAR file to the local repository.
mvn site: generate the project documentation.
mvn validate: validate the project’s POM and configuration.
mvn idea:idea: generate project files for IntelliJ IDEA or Eclipse.
mvn release:perform: Performs a release build.
mvn deploy: Copies the packaged JAR/ WAR file to the remote repository after compiling,
running tests and building the project.
mvn archetype:generate: This command is used to generate a new project from an
archetype, which is a template for a project. This command is typically used to create new
projects based on a specific pattern or structure.
mvn dependency:tree: This command is used to display the dependencies of the project
in a tree format. This command is typically used to understand the dependencies of the
project and troubleshoot any issues.

Generally, when we run any of the above commands, we add the mvn clean step so that
the target folder generated from the previous build is removed before running a newer
build. This is how the command would look on integrating the clean step with install
phase:
mvn clean install

Similarly, if we want to run the step-in debug mode for more detailed build information
and logs, we will add -X to the actual command. Hence, the install step with debug mode
on will have the following command:
mvn -X install

Consider a scenario where we do not want to run the tests while packaging or installing
the Java project. In this case, we use -DskipTests along with the actual command. If we
need to run the install step by skipping the tests associated with the project, the command
would be:
mvn install -DskipTests

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

2. Maven Profile
A Build profile is a set of configuration values, which can be used to set or override default
values of Maven build. Using a build profile, you can customize build for different
environments such as Production v/s Development environments.

Profiles are specified in pom.xml file using its activeProfiles/profiles elements and are
triggered in variety of ways. Profiles modify the POM at build time, and are used to give
parameters different target environments (for example, the path of the database server
in the development, testing, and production environments).

Types of Build Profile


Build profiles are majorly of three types.

Type Where it is defined


Per Project Defined in the project POM file, pom.xml
Per User Defined in Maven settings xml file (%USER_HOME%/.m2/settings.xml)
Global Defined in Maven global settings xml file
(%M2_HOME%/conf/settings.xml)

Profile Activation
A Maven Build Profile can be activated in various ways.
● Explicitly using command console input.
● Through maven settings.
● Based on environment variables (User/System variables).
● OS Settings (for example, Windows family).
● Present/missing files.

Profile Activation Examples


Let us assume the following directory structure of your project −

Maven Build Profile

Now, under src/main/resources, there are three environment specific files –


Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

Explicit Profile Activation


In the following example, we will attach maven-antrun-plugin:run goal to test the phase.
This will allow us to echo text messages for different profiles. We will be using pom.xml
to define different profiles and will activate profile at command console using maven
command.
Assume, we've created the following pom.xml in C:\MVN\project folder.

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<profiles> <profile>
<id>test</id>
<build>
<plugins> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions> <execution>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>Using env.test.properties</echo>
<copy file="src/main/resources/env.test.properties"
tofile="${project.build.outputDirectory}/env.properties"/>
</tasks>
</configuration> </execution> </executions>
</plugin> </plugins>
</build> </profile> </profiles>
</project>

Now open the command console, go to the folder containing pom.xml and execute the
following mvn command. Pass the profile name as argument using -P option.
C:\MVN\project>mvn test -Ptest

Maven will start processing and displaying the result of test build profile.
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

[INFO] --- maven-antrun-plugin:1.1:run (default) @ project ---


[INFO] Executing tasks
[echo] Using env.test.properties
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.011 s
[INFO] Finished at: 2024-05-10T20:29:39+05:30
[INFO] ------------------------------------------------------------------------

Now open the command console, go to the folder containing pom.xml and execute the
following mvn commands. Pass the profile names as argument using -P option.

C:\MVN\project>mvn test -Pnormal

C:\MVN\project>mvn test -Pprod


Check the output of the build to see the difference.

3. Maven Dependency Management Process

Dependency management in Maven allows teams to manage dependencies for multi-


module projects and applications. These can consist of hundreds or even thousands of
modules. Using Maven can help teams define, create, and maintain reproducible builds.

Why Dependency Management Is Important


Dependency management is important because the product you work on is built of over
50 components, produced by several teams working on different schedules. Some of
these components are more or less aligned on your product schedule. Others are
produced almost independently and you treat them like an external library. You need to
make sure you have the right versions of all of these components in your workspace in
order to develop, build, test, and release your product.

Dependency management is one of the most difficult parts of developing software and
related products.
We have two options for dependency management:
1. Create your own.
2. Use Maven for dependency management.

Maven manages both aspects (build phases and dependencies) starting from a single file
called pom.xml.

How Maven dependencies work


The image below, show Maven dependencies workflow during the entire build process.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Each step (represented by an arrow) moves the dependency from one point to the next.
A step is run by a phase execution.

Maven dependency management come from the pom.xml file, inside project’s root folder.
The dependencies list is written in the pom.xml.
This is a simple example:
<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/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.project-group</groupId>
<artifactId>project</artifactId>
<version>1.0</version>

<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.13</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>

</project>

Dependencies list start with <dependencies> tag and end with </dependencies>.

A single dependency starts with <dependency> tag and end with </dependency> and is
uniquely identified by the three element <groupId>, <artifactId> e <version> both in
Maven Central Repository (or others external) and in the local repository (after the
download).

Compile phase

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

During compile phase, Maven downloads dependencies from Maven Central Repository
(or from other repositories written in the settings.xml files) into the local repository, the
/.m2 folder. This folder is created the first time Maven downloads a dependency. From
that moment all dependencies will be downloaded here. Usually /.m2 path has this
structure:
>C:\Users\User Name\.m2

For example, consider a Java project containing in its root folder the pom.xml file seen in
the above paragraph. From this folder, type the following maven command from cmd:
>mvn compile

This means that Maven is downloading the dependencies list written in the pom.xml,
from the Maven Central Repository (or from others external repositories) into the local
\.m2 repository.

Package Phase
The classes and the functions inside dependencies, are used both to compile correctly the
code (as shown in the previous paragraph), either to be executed during application runs.
For this purpose, during this phase, project’s dependencies are copied inside the final
package (that is the actual application which can be a .jar, .war, .ear), following the steps
below:

Builds and puts the final package inside the /target folder, which was created during the
Compile Phase.

Finally, dependencies are copied from the /.m2 repository, directly inside the final
package, so their code can be used by the application at runtime.
From the folder containing the example pom.xml, type the following maven command
from cmd:
>mvn package

The jar goal from the “package phase”, creates the “projec-1-0.jar” in the /targed folder
in project’s workspace. This is the final package, which contains the same dependecies
used for the compile phase. Now dependencies code can be used while application runs.

Install Phase
At this point, the builded package is copied from the /target folder into the /.m2
repository. In this way the package itself can be used as a dependency by other local
projects.
From the folder containing the example pom.xml, type the following maven command
from cmd:
>mvn install

Steps to add dependencies in pom.xml

Before adding dependencies in pom.xml, you need to fulfil some prerequisites first.

Prerequisites: -
⮚ Eclipse IDE
⮚ Active Internet Connection
⮚ Maven installed for Eclipse IDE

Now, create a Maven project or if you have already created it, then go to pom.xml file and
open it.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Once you open it a tab will open in Eclipse IDE, in the footer section of the tab there is an
option for adding dependencies.

Click on Dependencies and a panel will open where you can add the required
dependencies for your project. Click on add button.

Once you click on add button a new window will open and you need to enter the name of
the dependency which you want to add to your project. After providing the necessary
details it will start searching the dependency inside the repository.

After the search gets finished it will display the search results to you. You need to select
the dependency and click on OK button and it will be added to your project.

For Example, I am going to add the dependency for Apache poi libraries. First of all, I need
to search for it then select the desired one and then add that dependency to my project.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

The first step is to search for the dependency.

The second step is to select the required dependency. Once you select the required
dependency its Group Id, Artifact Id and version will get displayed in the related text
fields.

Finally, click on OK button and the required dependency will get added to your project.
This process is time taking and complex because you need to search your required
dependency among all the search results and then only you can add it to your project.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

4. Introduction – Maven
Maven is a powerful project management tool that is based on POM (project object
model). It is used for projects build, dependency and documentation.

It simplifies the build process like ANT. But it is too much advanced than ANT.

Current version of Maven is 3.

There are many problems that we face during the project development. They are
discussed below:

1) Adding set of Jars in each project: In case of struts, spring, hibernate frameworks, we
need to add set of jar files in each project. It must include all the dependencies of jars also.

2) Creating the right project structure: We must create the right project structure in
servlet, struts etc, otherwise it will not be executed.

3) Building and Deploying the project: We must have to build and deploy the project so
that it may work.

Maven simplifies the above-mentioned problems. It does mainly the following tasks.

● It makes a project easy to build.


● It provides uniform build process (maven project can be shared by all the maven
projects).
● It provides project information (log document, cross referenced sources, mailing
list, dependency list, unit test reports etc.).
● It is easy to migrate for new features of Maven.

Apache Maven helps to manage,


● Builds
● Documentation
● Reporting
● SCMs
● Releases
● Distribution

Build Tool:

A build tool takes care of everything for building a process. It does the following:
● Generates source code (if auto-generated code is used).
● Generates documentation from source code.
● Compiles source code.
● Packages compiled code into JAR of ZIP file.
● Installs the packaged code in local repository, server repository, or central
repository.

Ant and Maven both are build tools provided by Apache. The main purpose of these
technologies is to ease the build process of a project.

There are many differences between ant and maven that are given below:
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

5. Maven Installation

We can download and install maven on windows, Linux and MAC OS platforms.

To install maven on windows, you need to perform following steps:


● Download maven and extract it.
● Add JAVA_HOME and MAVEN_HOME in environment variable.
● Add maven path in environment variable.
● Verify Maven.

Download Maven
To install maven on windows, you need to download Apache maven first.
Download Maven latest Maven software from http://maven.apache.org/download.cgi

Add MAVEN_HOME in environment variable


Right click on MyComputer -> properties -> Advanced System Settings -
> Environment variables -> click new button
Now add MAVEN_HOME in variable name and path of maven in variable value. It must
be the home directory of maven i.e. outer directory of bin. For example: E:\apache-
maven-3.1.1. It is displayed below:

Now click on OK button.


3) Add Maven Path in environment variable
Click on new tab if path is not set, then set the path of maven. If it is set, edit the path and
append the path of maven.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Here, we have installed JDK and its path is set by default, so we are going to append the
path of maven.
The path of maven should be %maven home%/bin. For example, E:\apache-maven-
3.1.1\bin.

4)Verify maven
To verify whether maven is installed or not, open the command prompt and write:
mvn −version
Now it will display the version of maven and jdk including the maven home and java
home.

6. Maven Repository

A maven repository is a directory of packaged JAR file with pom.xml file. Maven
searches for dependencies in the repositories. There are 3 types of maven repository:
1. Local Repository
2. Central Repository
3. Remote Repository

Maven searches for the dependencies in the following order:

Local repository then Central repository then Remote repository.

If dependency is not found in these repositories, maven stops processing and throws an
error.

1) Maven Local Repository


Maven local repository is located in your local system. It is created by the maven when
you run any maven command.

By default, maven local repository is %USER_HOME%/.m2 directory. For


example: C:\Users\SSS IT\.m2.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Update location of Local Repository


We can change the location of maven local repository by changing the settings.xml file.
It is located in MAVEN_HOME/conf/settings.xml, for example: E:\apache-maven-
3.1.1\conf\settings.xml.
Let's see the default code of settings.xml file.
settings.xml
...
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apa
che.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ${user.home}/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->

...
</settings>
Now change the path to local repository. After changing the path of local repository, it
will look like this:
settings.xml
1. ...
2. <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4. xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.
apache.org/xsd/settings-1.0.0.xsd">
5. <localRepository>e:/mavenlocalrepository</localRepository>
6.
7. ...
8. </settings>
As you can see, now the path of local repository is e:/mavenlocalrepository.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

2) Maven Central Repository


Maven central repository is located on the web. It has been created by the apache
maven community itself.

The path of central repository is: http://repo1.maven.org/maven2/.


The central repository contains a lot of common libraries that can be viewed by this
url http://search.maven.org/#browse.

3) Maven Remote Repository


Maven remote repository is located on the web. Most of libraries can be missing from the
central repository such as JBoss library etc, so we need to define remote repository in
pom.xml file.

Let's see the code to add the jUnit library in pom.xml 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/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>


<url>http://maven.apache.org</url>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
You can search any repository from Maven official website mvnrepository.com.

7. Maven pom.xml file


POM is an acronym for Project Object Model. The pom.xml file contains information of
project and configuration information for the maven to build the project such as
dependencies, build directory, source directory, test source directory, plugin, goals etc.

Maven reads the pom.xml file, then executes the goal.

Before maven 2, it was named as project.xml file. But, since maven 2 (also in maven 3), it
is renamed as pom.xml.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Elements of maven pom.xml file


Element Description

project It is the root element of pom.xml file.

modelVersion It is the sub element of project. It specifies the modelVersion. It


should be set to 4.0.0.

groupId It is the sub element of project. It specifies the id for the project
group.

artifactId It is the sub element of project. It specifies the id for the artifact
(project). An artifact is something that is either produced or used by
a project. Examples of artifacts produced by Maven for a project
include: JARs, source and binary distributions, and WARs.

version It is the sub element of project. It specifies the version of the artifact
under given group.

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/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-app</artifactId>
<version>1</version>

</project>

Maven pom.xml file with additional elements


Here, we are going to add other elements in pom.xml file such as:

Element Description

packaging defines packaging type such as jar, war etc.

name defines name of the maven project.

url defines url of the project.

dependencies defines dependencies for this project.

dependency defines a dependency. It is used inside dependencies.

scope defines scope for this maven project. It can be compile, provided,
runtime, test and system.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies> <dependency>
<groupId>junit</groupId> <artifactId>junit</artifactId>
<version>4.8.2</version> <scope>test</scope>
</dependency> </dependencies> </project>

8. Maven Plugins
The maven plugins are central part of maven framework, it is used to perform specific
goal. According to Apache Maven, there are 2 types of maven plugins.
● Build Plugins
● Reporting Plugins

Build Plugins
These plugins are executed at the time of build. These plugins should be declared inside
the <build> element.

Reporting Plugins
These plugins are executed at the time of site generation. These plugins should be
declared inside the <reporting> element.

Maven Core Plugins

Plugin Description

clean clean up after build.

compiler compiles java source code.

deploy deploys the artifact to the remote repository.

failsafe runs the JUnit integration tests in an isolated class loader.

install installs the built artifact into the local repository.

resource copies the resources to the output directory for including in the JAR.
s

site generates a site for the current project.

surefire runs the JUnit unit tests in an isolated class loader.

verifier verifies the existence of certain conditions. It is useful for integration tests.

To see the list of maven plugins, you may visit apache maven official website
http://repo.maven.apache.org/maven2/org/apache/maven/plugins/. Maven plugins
are also available outside the maven at codehaus.org and code.google.com.
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

9. Maven Eclipse Example


Maven eclipse tutorial explains how to create maven example in eclipse.
In eclipse, click on File menu → New → Project → Maven → Maven Project. → Next → Next
→ Next. Now write the group Id, artifact Id, Package as shown in below figure → finish.

Now you will see a maven project with complete directory structure. All the files will be
created automatically such as Hello Java file, pom.xml file, test case file etc. The directory
structure of the maven project is shown in the below figure.

Now you can see the code of App.java file and run it. It will be like the given code:
package com.javatpoint;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{ System.out.println( "Hello World!" ); } }

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

If you right click on the project → Run As, you will see the maven options to build the
project.

10. Maven – Project Creation

Maven uses archetype plugins to create projects. To create a simple java application,
we'll use maven-archetype-quickstart plugin. In example below, we'll create a maven-
based java application project in C:\MVN folder.
Let's open the command console, go to the C:\MVN directory and execute the
following mvn command. Make sure that C:\MVN directory is empty before running the
command.

C:\MVN>mvn archetype:generate
-DgroupId = com.companyname.bank
-DartifactId = consumerBanking
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false

Maven will start processing and will create the complete java application project
structure.
C:\MVN>mvn archetype:generate -DgroupId=com.companyname.bank -
DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -
DinteractiveMode=false
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @
standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @
standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.2.0: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: basedir, Value: C:\MVN
[INFO] Parameter: package, Value: com.companyname.bank
Downloaded by visali soundrrajan13 ([email protected])
lOMoARcPSD|15103529

[INFO] Parameter: groupId, Value: com.companyname.bank


[INFO] Parameter: artifactId, Value: consumerBanking
[INFO] Parameter: packageName, Value: com.companyname.bank
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\consumerBanking
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.396 s
[INFO] Finished at: 2021-12-13T15:13:00+05:30
[INFO] ------------------------------------------------------------------------

C:\MVN>
Now go to C:/MVN directory. You'll see a java application project created, named
consumer Banking (as specified in artifactId). Maven uses a standard directory layout as
shown below −

Using the above example, we can understand the following key concepts −
Sr.No. Folder Structure & Description

consumerBanking
1
contains src folder and pom.xml

src/main/java
2
contains java code files under the package structure (com/companyName/bank).

src/main/test
3 contains test java code files under the package structure
(com/companyName/bank).

src/main/resources
4 it contains images/properties files (In above example, we need to create this
structure manually).

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

If you observe, you will find that Maven also created a sample Java Source file and Java
Test file. Open C:\MVN\consumerBanking\src\main\java\com\companyname\bank
folder, you will see App.java.

package com.companyname.bank;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ){
System.out.println( "Hello World!" ); }}

Open C:\MVN\consumerBanking\src\test\java\com\companyname\bank folder to see


AppTest.java.

package com.companyname.bank;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
* Unit test for simple App.
*/
public class AppTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName ) {
super( testName );
}

/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite( AppTest.class );
}

/**
* Rigourous Test :-)
*/
public void testApp() {
assertTrue( true );
}}

Developers are required to place their files as mentioned in table above and Maven
handles all the build related complexities.

11. Installation of Gradle & Understand build using Gradle


<<Refer Ex. 6 in Lab Record>>

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

12. Maven create and build Artifacts

In Maven, you can create and build artifacts using the package phase of the build lifecycle.
The package phase is responsible for taking the compiled code and other project
resources and packaging them into a distributable format, such as a JAR (Java Archive),
WAR (Web Application Archive), or other custom formats.

Here are the steps to create and build artifacts using Maven:
Configure the Build Output: In your project's pom.xml file, you need to configure the
output of the build. This includes specifying the type of artifact you want to create (e.g.,
JAR, WAR) and any additional resources to include. You do this in the <build> section of
your pom.xml:

<build>
<finalName>my-artifact</finalName> <!-- Name of the artifact without the extension --
>
<plugins> <!-- Plugin configurations for creating the artifact -->
<!-- For example, maven-jar-plugin or maven-war-plugin -->
</plugins> </build>

Depending on your project type and requirements, you would use different plugins (e.g.,
maven-jar-plugin for JAR projects or maven-war-plugin for web applications).

Run the Build: To create and build the artifact, you run the Maven build command. Open
a command prompt or terminal in your project's directory and execute:
mvn clean package

clean: This goal removes the target directory, which contains the output of previous
builds. It ensures that you start with a clean slate.

package: This goal is responsible for creating the artifact as specified in your project's
pom.xml.

Review the Output: After running the Maven command, you'll find the built artifact in
the target directory within your project's root directory. The name of the artifact is
usually determined by the <finalName> configuration in your pom.xml file.

Deploy or Use the Artifact: Depending on your project's requirements, you can deploy
the generated artifact to a repository, use it in other projects, or distribute it as needed.

Here's a more detailed example for creating a JAR artifact:


<project> <!-- ... --> <build>
<finalName>my-jar-artifact</finalName>
<plugins> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration> <archive>
<manifest> <mainClass>com.example.MainClass</mainClass>
</manifest> </archive> </configuration> </plugin>
</plugins> </build> <!-- ... --> </project>

In this example, the maven-jar-plugin is configured to create a JAR artifact with a


specified main class in the manifest file. When you run mvn clean package, it will generate
a JAR file with the name my-jar-artifact.jar in the target directory.

Downloaded by visali soundrrajan13 ([email protected])


lOMoARcPSD|15103529

Remember that Maven is highly configurable, and you can customize the build process,
including artifact creation, to meet the specific needs of your project.

Downloaded by visali soundrrajan13 ([email protected])

You might also like