Unit II Compile and Build Using Maven & Gradle
Unit II Compile and Build Using Maven & 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
UNIT - II
Maven is a simple build automation tool which is used with Java projects. Maven is also defined as a comprehensive project management
tool. It aims to provide the developers a complete and detailed build life cycle framework of an application. (Based on the concept of a
project object model (POM))
1) Maintain Structure
2) Build Code
3) Dependency Management
2. The dependencies, plug-ins & profiles that the project is associated in a standalone or a distributed environment.
Important Terminology:
1) Group ID - A unique base name of the company or group that created the project
4) Dependencies - Dependencies are the libraries, which are needed by the project like JAR, ZIP, etc.,
Dependency Management: One of the most significant challenges is managing external dependencies. Without Maven, developers must
manually download, configure, and include libraries and dependencies, which can be error-prone and time-consuming.
Build Process Complexity: Building the project without a build automation tool like Maven can lead to a complex and non-standardized
build process. This can result in inconsistencies, making it harder for team members to collaborate effectively.
Version Control: Without Maven's standardized project structure, it becomes more challenging to manage version control for the project.
Inconsistent directory structures and manually managed dependencies can lead to version conflicts and compatibility issues.
Lack of Convention: Maven promotes convention over configuration, meaning that it follows a standardized project structure and naming
conventions. Without it, team members may spend more time discussing and deciding on project configurations, which can slow down
development.
UNIT - II
Documentation: Maven automatically generates documentation, which is beneficial for project maintainability.
Without it, developers may need to invest extra time and effort in manually creating and updating
documentation.
Plugin Ecosystem: Maven offers a wide range of plugins for various tasks, such as code analysis, code coverage,
and deployment. Without Maven, developers may need to use third-party tools and plugins or create their
own, leading to additional complexity.
Integration with IDEs: Most popular Integrated Development Environments (IDEs) have built-in support for
Maven, making it easier to manage projects. Without Maven, developers may need to configure IDEs manually,
which can be time-consuming.
UNIT - II
• Maven uses Convention over Configuration, which means developers are not required to create build process themselves.
• Developers do not have to mention each and every configuration detail. Maven provides sensible default behavior for
projects. When a Maven project is created, Maven creates default project structure. Developer is only required to place
files accordingly and he/she need not to define any configuration in pom.xml.
Following table shows the default values for project source code files, resource files and other configurations. ${basedir}
denotes the project location −
UNIT - II
Features of Maven
• Extensible, with the ability to easily write plugins in Java or scripting languages.
• Model-based builds − Maven is able to build any number of projects into predefined output types such as jar, war,
metadata.
• Coherent site of project information − Using the same metadata as per the build process, maven is able to generate a
website and a PDF including complete documentation.
UNIT - II
• Release management and distribution publication − Without additional configuration, maven will integrate
with your source control system such as CVS and manages the release of a project.
• Backward Compatibility − You can easily port the multiple modules of a project into Maven 3 from older
versions of Maven. It can support the older versions also.
• Automatic parent versioning − No need to specify the parent in the sub module for maintenance.
• Parallel builds − It analyzes the project dependency graph and enables you to build schedule modules in
parallel. Using this, you can achieve the performance improvements of 20-50%.
• Better Error and Integrity Reporting − Maven improved error reporting, and it provides you with a link to the
Maven wiki page where you will get full description of the error.
UNIT - II
Mavan Installation:
Refer - mkyong.com
UNIT - II
Maven Architecture:
• It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as
pom.xml.
• The POM contains information about the project and various configuration detail used by Maven to build
the project(s).
• POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the
current directory. It reads the POM, gets the needed configuration information, and then executes the
goal.
• Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its
version as these attributes help in uniquely identifying the project in repository.
UNIT - II
The following tables lists some of the configuration that can be specified in the POM.
UNIT - II
POM 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.ecommerce</groupId>
<artifactId>Aravid</artifactId>
<version>1.0</version>
</project>
*All POM files require the project element and three mandatory fields: groupId, artifactId, version.
UNIT - II
Maven provides a well-defined build lifecycle that consists of a sequence of phases and goals. These phases and goals are executed in a specific
order, allowing you to build, test, package, and deploy your projects with ease.
1. Clean Phase: This phase removes all files generated by previous builds, such as compiled classes and build artifacts. It provides a clean slate
for the project.
2. Validate Phase: In this phase, Maven validates the project's structure and configuration. It checks if the pom.xml file is valid and if the
required dependencies are available.
3. Compile Phase: This phase compiles the project's source code, generating the corresponding class files. These files are placed in the
target/classes directory by default.
4. Test Phase: In this phase, Maven executes the project's unit tests. It uses a testing framework like JUnit to run test cases. Failures in this phase
will prevent the build from progressing further.
5. Package Phase: In this phase, Maven packages the compiled classes and resources into a distributable format according to the project's
packaging type (e.g., JAR, WAR, or others). The resulting artifact is stored in the target directory.
UNIT - II
6. Integration Test Phase: This phase is responsible for running integration tests. It typically involves deploying the
application and executing tests that span multiple components or services.
7. Verify Phase: In this phase, Maven performs additional checks on the project, such as checking code quality and
generating reports. It ensures that the project meets quality standards.
8. Install Phase: Maven installs the project's artifact into the local Maven repository (~/.m2/repository). This makes it
available for other projects on your local machine to use as a dependency.
9. Deploy Phase: If your project needs to be deployed to a remote repository, this phase handles the deployment
process. It
copies the artifact to a remote repository for sharing with others or for deployment to production servers.
These are the standard phases in the Maven build lifecycle. You can invoke these phases using Maven commands (e.g., mvn
clean, mvn compile, etc.). Additionally, you can bind your own custom goals and plugins to specific phases to extend or
modify the build process to meet your project's requirements. Maven's build lifecycle ensures a consistent and reliable build
process for your projects.
UNIT - II
The default lifecycle is the most commonly used one and is responsible for building, testing, and packaging the project. It includes the following phases:
• Validate: Validates the project's configuration and dependencies.
• Compile: Compiles the project's source code.
• Test: Executes unit tests for the project.
• Package: Packages the compiled code and resources into a distributable format (e.g., JAR or WAR).
• Verify: Performs additional checks and generates reports to ensure code quality.
• Install: Installs the project's artifact in the local Maven repository.
• Deploy: Deploys the project's artifact to a remote repository (if needed).
2. Clean:
The clean life cycle handles project cleaning. The clean phase consists of the following three steps:
• Pre-clean
• Clean
• Post-clean
• The mvn post-clean command is used to invoke the clean lifestyle phases in Maven.
UNIT - II
3. Site:
The Maven site plugin handles the project site's documentation, which is used to create reports, deploy sites, etc.
needed). Ultimately, the site that is created contains the project report.
Each phase in these lifecycles corresponds to a specific goal or set of goals. By running a
Maven command, you can specify a
phase, and Maven will execute all the preceding phases as well, ensuring that the build
process is consistent and complete.
UNIT - II
Maven Profile:
Maven profiles are a powerful feature that allows you to customize your Maven build process based on different environments, build
configurations, or other criteria. They provide a way to define and activate specific sets of configuration settings, dependencies, and plugins
for different scenarios. Maven profiles are defined in the project's pom.xml file and can be activated manually or automatically based on
conditions.
To define a profile in your pom.xml file, you use the <profiles> element and specify the configuration within the <profile> tags.
Maven Repository:
A Maven repository is a directory to store all the project jars, library jar, plugins or any other artifacts.
For maven to download the required artifacts of the build and dependencies (jar files) and other plugins which are
configured as part of any project, there should be a common place where all such artifacts are placed. This common shared
area is called as Repository in maven.
Local Repository: The repository which resides in our local machine which are cached from the remote/central
repository downloads and ready for the usage. The folder to hold/place all the dependencies in local can be
configured in the settings.xml file of the maven folder under the tag <localRepository>.
Ex:
<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.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>D:/m2repo</localRepository>
</settings>
UNIT - II
Central Repository: This is the repository provided by maven community. This repository contains large set of commonly used/required
libraries for any java project. Basically, internet connection is required if developers want to make use of this central repository. But, no
configuration is required for accessing this central repository.
Ex:
<repositories>
<repository>
<id>central.repository</id>
<url>http://repo1.maven.org/maven2/</url>
</repository>
</repositories>
UNIT - II
Remote Repository: This repository as the name suggests resides in the remote server (which is developer's own
custom repository containing required libraries or other project jars.) and which can be accessed by using
different file transfer protocols like file:// or http://. Remote repository will be used for both downloading and
uploading the dependencies and artifacts.
Ex:
<repositories>
<repository>
<id>remote.repository</id>
<url>http://download.ogrname.com/maven2/</url>
</repository>
</repositories>
UNIT - II
When we execute Maven build commands, Maven starts looking for dependency libraries in the following
sequence −
Step 1 − Search dependency in local repository, if not found, move to step 2 else perform the further processing.
Step 2 − Search dependency in central repository, if not found and remote repository/repositories is/are
mentioned then move to step 4. Else it is downloaded to local repository for future reference.
Step 3 − If a remote repository has not been mentioned, Maven simply stops the processing and throws error
(Unable to find dependency).
Step 4 − Search dependency in remote repository or repositories, if found then it is downloaded to local
repository for future reference. Otherwise, Maven stops processing and throws error (Unable to find
dependency).
UNIT - II
Maven Plugins:
Plugin in maven is the one of the vital feature that is basically used to reuse the common build logic across different projects.
Plugins are the ones through which all the tasks like compiling code, testing them with the junits, creating jar/war/ear files
and documentation of the projects are carried out. Most of the work in maven is done using plugins, since the dependencies
(jar files) are added only to the classpath while executing tasks.
So, maven is nothing but a plugin execution framework in which every tasks are accomplished by the usage of plugins.
Below are the basic list of tasks that are handled by plugins in maven :
• Code compilation
• Project documentation
UNIT - II
Behavior of any plugin can be changed using a set of parameters exposed by each plugin goal (also known as
Mojo). A Mojo in maven is just a goal, basically specifies the metadata of a goal - goal name, which phase it fits
into and parameters expected by the goal.
1. Build Plugins - Basically these plugins will execute during the build phase. These plugins are defined
under the <build> element in pom.xml
2. Report Plugins - These plugins are executed during the site generation (report or javadocs generation)
phase. These plugins will be configured under the <reporting> element in pom.xml
UNIT - II
Ex:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source> <!-- Java source version -->
<target>1.8</target> <!-- Java target version -->
</configuration>
</plugin>
</plugins>
</build>
UNIT - II
Maven is a powerful build tool and project management tool used primarily for Java projects. It is used to manage
dependencies, compile code, and create artifacts such as JAR (Java Archive) files.
1. Project Setup: First, you need to set up your Maven project. This typically involves creating a project
directory structure with a pom.xml file, which defines the project's configuration and
dependencies.
2. POM.xml Configuration: In the pom.xml file, you specify the project's metadata, dependencies, and build
settings. You can define the project's packaging type, which could be JAR for a Java library, WAR for a
web application, or other formats.
UNIT - II
3. Dependency Resolution: Maven will automatically download and manage the project's dependencies based
on the specifications in the pom.xml file. It retrieves the required JAR files from a central repository or
other specified repositories.
4. Compilation: When you run the mvn compile command, Maven compiles your Java source code,
producing class files. These class files are stored in the target directory by default.
5. Testing: You can run tests on your code using the mvn test command. Maven executes test cases and
reports
the results.
6. Packaging: To create an artifact (such as a JAR file), you use the mvn package command. This step takes the
compiled classes and resources and packages them according to the project's packaging type (e.g.,
JAR).
7. Install: If you want to install the artifact in your local Maven repository, you can use the mvn install
UNIT - II
8. Deployment: For distributing your artifact to a remote repository, you would configure Maven to deploy it
using the mvn deploy command. This is often used when sharing your library with others or deploying a
web application to a server.
9. Customization: You can customize the build process by adding plugins to your pom.xml file. Plugins can
perform various tasks, such as code generation, code analysis, or even custom packaging.
Remember that Maven's power lies in its convention-over-configuration approach. By following standard
directory structures and naming conventions, you can create and build artifacts without needing to specify every
detail in your build configuration.
UNIT - II
• Maven has built-in dependency management. We can just specify in the POM file what external libraries the
project depends on, and which version.
• All the basic list of dependencies in maven is handled by the maven repository at which a project downloads
the required dependencies. But, there will be certain scenario at which some particular dependencies may not
be available in the maven remote and central repositories. Maven still answers this scenario by providing the
feature of external dependency management.
• If these external libraries need other libraries, then Maven would download their dependency libraries into
your local Maven repository as well.
• We can specify dependencies inside the dependencies element in the POM file.
UNIT - II
Ex:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>
UNIT - II
An external dependency can be such as sqljdbc.jar. In maven, any external dependencies can be easily
configurable as other dependencies in the pom.xml file. So, let us see a simple example to add sqljdbc.jar as an
external dependency into a maven project.
• Create a folder called lib in the maven project.
• Now, open the pom.xml of the project and add a new dependency as shown below:
Ex:
<dependency>
<groupId>sqljdbc</groupId>
<artifactId>sqljdbc</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${basedir}\src\lib\sqljdbc.jar</systemPath>
</dependency>
UNIT - II
Dependency Scope:
Dependency scope in maven is classified into 5 different types. Each of these scope controls the dependencies
that are available in the class path and dependencies that are included in the application.