Creating JAR and WAR Files Using Gradle
Gradle is a powerful build automation tool widely used for Java applications. It allows developers to compile code, manage dependencies, run tests, and package applications into distributable formats such as JAR and WAR files.
What is a JAR File?
A JAR (Java ARchive) file is a compressed package that contains:
- Compiled .class files
- Resource files (properties, images, etc.)
- A manifest file (MANIFEST.MF)
JAR files are commonly used for:
- Standalone Java applications
- Libraries and utilities
- Microservices (e.g., Spring Boot JARs)
Creating a JAR File Using Gradle
1. Apply the Java Plugin
Gradle can generate a JAR automatically when the Java plugin is applied.
build.gradle
plugins {
id 'java'
}2. Project Structure
📁project-name
📁src
📁main
📁java
📄build.gradle
3. Build the JAR
Run the following command:
terminal
gradle buildThe JAR file will be created at: build/libs/project-name.jar
4. Customizing the JAR (Optional)
build.gradle
jar {
archiveBaseName = 'my-application'
archiveVersion = '1.0.0'
manifest {
attributes(
'Main-Class': 'com.example.MainClass'
)
}
}What is a WAR File?
A WAR (Web Application ARchive) file is used to deploy Java web applications to servlet containers like:
Apache Tomcat
Jetty
WildFly
A WAR file contains:
- Servlets and controllers
- JSP files
- HTML, CSS, JavaScript
- WEB-INF configuration files
Creating a WAR File Using Gradle
1. Apply the WAR Plugin
build.gradle
plugins {
id 'java'
id 'war'
}2. Project Structure
📁project-name
📁src
📁main
📁java
📁webapp
📄index.jsp
📁WEB-INF
📄web.xml
📄build.gradle
3. Build the WAR
Run:
terminal
gradle buildThe WAR file will be generated at: build/libs/project-name.war
4. Customizing the WAR
build.gradle
war {
archiveBaseName = 'my-web-app'
archiveVersion = '1.0'
}JAR vs WAR: Key Differences
JAR Files
- Standalone Java applications
- Contains compiled classes and resources
- Can be executed directly with java -jar
- Used for libraries and microservices
WAR Files
- Web applications for servlet containers
- Contains web resources (JSP, HTML, CSS)
- Requires deployment to a server
- Includes WEB-INF directory structure
