Maven
Last updated
Was this helpful?
Last updated
Was this helpful?
Maven is a widely-used build automation tool for Java projects. It simplifies the process of building and managing Java applications by providing a standard project structure, dependency management, and build lifecycle.
Maven uses a project object model (POM) file, typically named pom.xml
, to define project configuration and dependencies. It downloads dependencies from remote repositories, compiles source code, and packages the project into a distributable format.
To install Maven, follow these steps:
Download Maven: Visit the Apache Maven download page () and download the latest binary distribution for your operating system.
Extract Maven:
On Windows: Extract the downloaded archive to a directory (e.g., C:\Program Files\apache-maven-x.y.z
).
On Linux or macOS: Use tar
to extract the archive to a directory (e.g., /opt/apache-maven-x.y.z
).
Set Environment Variables:
On Windows: Add the M2_HOME
and MAVEN_HOME
environment variables, and add %M2_HOME%\bin
to your PATH
.
On Linux or macOS: Add the following lines to your shell profile file (~/.bashrc
, ~/.bash_profile
, or ~/.zshrc
):
Verify Installation: Open a new terminal window and run mvn -version
to verify that Maven is installed correctly.
A typical Maven project has a well-defined directory structure, which makes it easy to manage and build. Here's a simplified project structure:
Let's create a simple Maven project:
Open a Terminal/Command Prompt.
Navigate to the Directory Where You Want to Create the Project.
Create a New Maven Project: Run the following command to create a new Maven project:
Replace com.example
and my-maven-project
with your desired group ID and project name.
Navigate to the Project Directory:
View the Project Structure: You'll see the project structure similar to what was described earlier.
Maven simplifies dependency management. To add dependencies to your project, edit the pom.xml
file and add the following dependency block inside the <dependencies>
element:
For example, to add the Apache Commons Lang library, your pom.xml
would include:
After editing the pom.xml
, run mvn clean install
to download the dependencies.
To build and package your Maven project, use the following Maven goals:
Clean: Removes the target
directory.
Compile: Compiles the source code.
Test: Runs tests.
Package: Packages the project (e.g., creates a JAR or WAR file).
Install: Installs the project artifact to your local repository.
These are some of the most common Maven goals. You can execute these commands in your project's root directory.
Maven's capabilities extend far beyond what's covered here, but this guide should give you a solid foundation for managing and building your Java projects with Maven.