Streamlining Java Builds with Jenkins: A Step-by-Step Guide
Before diving into this hands-on guide, I recommend reading my first blog, ‘CI/CD Journey with Jenkins: An Introduction to Efficient Build Pipelines,’ which you can find to get a foundational understanding of Jenkins and CI/CD workflows. Learn Streamlining Java Builds with Jenkins: A Step-by-Step Guide to automate builds, optimize CI/CD pipelines, and enhance development efficiency.
Now that you’re familiar with the fundamentals of CI/CD pipelines from the previous blog, let’s dive deeper into a hands-on approach. In this guide, we’ll focus on streamlining Java builds with Jenkins. I will walk you through the step-by-step process of setting up Jenkins for Java-based projects, optimizing your build process, and ensuring that your CI/CD pipeline runs efficiently. By the end of this blog, you’ll have the skills to integrate Jenkins into your Java development workflow, enabling quicker and more reliable deployments.
This blog suggests a more practical, tutorial-based approach, where you walk the readers through the setup and usage of Jenkins for Java build automation.
What is Jenkins?
Building, testing, and deploying software applications is made easier with Jenkins server.
It is written in Java and is widely used for automating various stages of software development, such as code compilation, testing, deployment, and delivery. Jenkins supports multiple plugins to enhance its functionality and is compatible with many source control systems, including Git, Subversion, and Mercurial.
Why Use Jenkins with Java Programs?
Making sure the code is efficient and of high quality is essential while creating Java applications. Jenkins can help you automate the following tasks:
- Build Automation: Automatically compile and build Java projects.
2 . Testing: Run unit tests (e.g., using JUnit) on every code commit.
3 . Deployment: Deploy Java applications to different environments.
4 . Continuous Integration: Monitor code changes, detect errors early, and integrate them quickly.
By using Jenkins with Java programs, you can increase productivity, reduce errors, and accelerate your development lifecycle.
Setting Up Jenkins for Java Projects
Let’s go through the steps to set up Jenkins and integrate it with a simple Java program.
Steps:
Download Jenkins: Go to Jenkins Downloads and download the appropriate installer based on your operating system. I have used the Windows installer. You can download from here:
https://www.jenkins.io/download/
Install Jenkins: Follow the installation steps based on your OS. After installation, Jenkins will start running on your local server (by default, it is hosted on http://localhost:8080).
Unlock Jenkins: Once Jenkins is running, open the URL in a browser. You will be asked to unlock Jenkins by entering the administrator password, which is located in the Jenkins installation folder.
Install Suggested Plugins: During the setup process, Jenkins will prompt you to install plugins. It is recommended to install the suggested plugins to get started quickly.
Keep following the installation steps until you reach the Jenkins dashboard.
Go to Dashboard > Manage Jenkins > Plugins and select Available Plugins options.
Search for Maven plugins. Select Maven Integration, Pipeline Maven IntegrationVersion, Pipeline Maven Plugin APIVersion.After it, click on install.
To build your Java project using Jenkins, we need to install Java JDK, Maven, and Git client.
These tools will be used when we create the Jenkins pipeline.
Go to Dashboard > Manage Jenkins > Tools
- Add the JDK installation path as shown below
- Ensure that git is configured as below:
- Add the Maven installation path as shown below.
Create a Java Project with Maven in Eclipse:
Add a new Java file DemoArraySum.java in project projectArray with the code below:
package com.sm.projectArray;
public class DemoArraySum {
public int findSumArray(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
public int findMaxArray(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException(“Array cannot be null or empty”);
}
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
return max;
}
public static void main(String[] args) {
DemoArraySum ob=new DemoArraySum();
int arr[]= {4,2,7,5,8,6};
int s=ob.findSumArray(arr);
System.out.println(s);
int m=ob.findMaxArray(arr);
System.out.println(m);
}
}
Add Unit Test: Add a basic unit test in the src/test/java directory.
package com.sm.projectArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class DemoArraySumTest {
private final DemoArraySum demoArray = new DemoArraySum();
@Test
public void testSumArray() {
int[] arr = {1, 2, 3, 4, 5};
int result = demoArray.findSumArray(arr);
assertEquals(15, result, “The sum of the array elements should be 15”);
}
@Test
public void testMaxArray() {
int[] arr = {1, 2, 3, 4, 5};
int result = demoArray.findMaxArray(arr);
assertEquals(5, result, “The maximum value in the array should be 5”);
}
@Test
public void testMaxArrayEmpty() {
int[] arr = {};
assertThrows(IllegalArgumentException.class, () -> {
demoArray.findMaxArray(arr);
}, “Array cannot be null or empty”);
}
}
Push the code in Git repository.
The code above has been shared at https://github.com/kiranlkw/javaprojectarray.git
Create a Jenkins Freestyle Project called javaBuildJob for the CI/CD process for the Maven project.
Select the javaBuildJob and configure it.
Select Source Code Management and configure the github repository above for the job.
Configure the Maven goal in the Build Steps.
Ensure that you provide a path to the pom.xml file. The build process by default would look at the GitHub root directory location for the pom.xml.
So the Goals would be formatted as “-f projectArray/pom.xml clean install” in this example.
Select the Maven3.9 version configured in Jenkins while configuring Maven tools in the Jenkins Tools Configuration steps above.
Configure the Build Triggers to define when the Jenkins job is supposed to run. This configures when the job runs automatically to execute the configured build steps.
(You can always manually trigger the pipeline as well)
Save the configuration.
Run the job to verify that the job executes the steps as expected.
Click “Build Now”.
Check the Build progress
You can check the Build progress of the job run by selecting it under the Builds section. The output of the Maven build can be seen by selecting “Console Output” on the side menu of the specific job run.
In conclusion, automating Java builds through a CI/CD pipeline significantly streamlines the development process, enhancing both productivity and quality. By integrating tools like Jenkins for continuous integration and deployment, we’ve ensured that every code change undergoes consistent, automated builds and tests, reducing the risk of human error and inconsistency. This not only accelerates feedback loops but also allows for faster identification and resolution of issues, improving the overall efficiency of the development cycle.
The seamless integration of automated testing ensures that any bugs are caught early, while automated deployment facilitates continuous delivery, making it easier to release stable, production-ready code. The use of version control and artifact management ensures that every build is traceable and deployable, enabling smooth rollbacks if necessary.
Furthermore, CI/CD practices support scalability, allowing the pipeline to handle multiple branches and projects without manual intervention. This enables teams to focus more on innovation and less on repetitive tasks, driving higher-quality software and faster delivery.
By adopting CI/CD for Java builds, we’ve built a robust and reliable development pipeline that supports rapid and consistent software delivery while minimizing errors and manual overhead. This approach is essential for maintaining agility and competitiveness in today’s fast-paced software development environment.
To explore more do visit: Click Here
Author:-
Kiran Tiwari
Call the Trainer and Book your free demo Class For DevOps Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.