Java and Maven Builds
Learn how to configure Jenkins to compile, test, package, and automate Java applications using Apache Maven and the Jenkins Global Tool Configuration.
What is Java and Maven Integration in Jenkins?
Java applications require a Java Development Kit (JDK) to compile code and a build automation tool like Apache Maven to manage dependencies, coordinate lifecycles, and package final outputs into JAR or WAR files.
Integrating Maven with Jenkins ensures that your application lifecycle—from standard compilations down to artifact deployments—runs deterministically inside an isolated CI/CD environment. This prevents local compilation quirks from slipping through to production environments.
Key Concepts
POM Object Model (pom.xml)
The core project configuration file read by Maven that controls app dependencies, plug-in extensions, and target packaging parameters.
Maven Lifecycle Phases
Standard target actions mapped to your pipeline steps such as mvn clean, mvn test, and mvn package.
Global Tool Configuration
Defining JDK and Maven installations within the Jenkins controller settings so individual nodes can download and isolate runtimes on-demand.
Dependency Caching
Configuring agents to retain local .m2/repository caches to accelerate consecutive pipeline build iterations.
Practical Jenkins Example
This declarative pipeline demonstrates how to declare explicitly managed versions of JDK and Maven to run linting, unit tests, and code packaging steps:
pipeline {
agent any
tools {
// Automatically configures predefined versions from Jenkins Global Tool Configurations
jdk 'OpenJDK-17'
maven 'Maven-3.9'
}
stages {
stage('Initialize & Validate') {
steps {
echo 'Checking Runtime Environment...'
sh 'java -version'
sh 'mvn -version'
}
}
stage('Execute Tests') {
steps {
echo 'Running unit test suite...'
// Cleans old targets and runs tests defined in pom.xml
sh 'mvn clean test'
}
}
stage('Package Application') {
steps {
echo 'Compiling binaries into distribution formats...'
// Skips unit tests to save execution overhead during packaging
sh 'mvn package -DskipTests'
}
}
stage('Archive Target Artifacts') {
steps {
echo 'Saving compiled JAR files to Jenkins Controller...'
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true
}
}
}
}
Practice Exercise
- Navigate to Manage Jenkins → Tools and verify your configured names under JDK and Maven match your script labels.
- Create a new Pipeline job in Jenkins named
java-maven-build-pipeline. - Paste the declarative pipeline script above, substituting your specific Java and Maven environment identifiers if necessary.
- Run the build, open the Console Output, and review the standard Maven outputs downloading dependencies and creating target build artifacts.
Summary
You have completed the Java and Maven Builds lesson. Knowing how to run standard Maven targets inside structured steps enables you to seamlessly manage advanced enterprise patterns like microservice frameworks.