Apache Maven is a build automation tool primarily used for Java projects. It simplifies project setup, dependency management, and builds automation. Maven uses an XML configuration file called pom.xml
(Project Object Model) to define project structure, dependencies, and build lifecycle. It’s widely used in the Java ecosystem because of its simplicity and powerful dependency management features.
Concepts of Maven
- POM (Project Object Model): The
pom.xml
file is the core of any Maven project. It contains configuration information such as project dependencies, plugins, and build settings. - Repository: Maven uses repositories to store and manage project dependencies. These can be local (on your machine) or remote (online). Maven central is the most commonly used remote repository.
- Artifacts: Artifacts are packaged versions of your project or dependencies. Typically, Maven uses
.jar
files for Java libraries or.war
for web applications. - Maven Goals and Phases: Maven executes a series of tasks, known as goals, that are grouped into phases. These phases define the build lifecycle of a project (e.g.,
compile
,test
,package
).
Setting Up a Maven Project
Install Maven: To get started, download and install Apache Maven from the official website. After installation, verify it by running:
1 |
mvn -v |
Create a New Maven Project: We can create a Maven project using the following command, which generates a sample project structure:
1 |
mvn archetype:generate -DgroupId=com.example -DartifactId=my-first-maven-project -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false |
This will create a directory called my-first-maven-project
, with the necessary Maven project structure:
src/main/java
: Your source codesrc/test/java
: Your test codepom.xml
: Maven configuration file
Add Dependencies: To add a dependency, open the pom.xml
file and insert the dependency inside the <dependencies>
tag. For example, to add JUnit for unit testing:
1 2 3 4 5 6 7 8 |
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> </dependencies> |
Build the Project: To compile and build your project, run
1 |
mvn clean install |
This command will clean the previous build files and install the project artifacts into our local repository.