Last Updated : 23 Jul, 2025
Optional dependencies in Maven are used when it is difficult to break up a project into sub-modules (for whatever reason). The idea is that some dependencies are only required for specific aspects of the project and will be removed if such features are not used. Ideally, such a feature would be separated into a sub-module that is dependent on the main functionality project. The only dependencies in this new subproject would be non-optional as using the subproject's functionality requires you to have all of them.
The project cannot be split up (for whatever reason), and these dependencies are marked optional. If a user wants to access the functionality associated with an optional dependency, they must redeclare the dependency in their project.
Apply <optional> to DependenciesYou can't separate the producer project into submodules, you can apply <optional> to dependencies that enable additional behavior, as seen in the POM file below.
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="https://maven.apache.org/POM/4.1.2 https://maven.apache.org/xsd/maven-4.1.2.xsd"
xmlns="https://maven.apache.org/POM/4.1.2"
xmlns:xsi="https://www.w3.org/2021/XMLSchema-instance">
<modelVersion>4.1.2</modelVersion>
<groupId>com.acme</groupId>
<artifactId>producer</artifactId>
<version>1.2.1</version>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>org.geeksforgeeks</groupId>
<artifactId>guava</artifactId>
<version>29.1-jre</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>
Why use Optional Dependencies?
Optional dependencies save both space and memory. They prohibit problematic jars that violate a licensing agreement or create classpath difficulties from being packed into a WAR, EAR, fat jar, or similar format.
Use of the optional tagTo make a dependence optional, put the <optional> element to true in the declaration:
<project> <dependencies> <dependency> <groupId>sample.ProjectA</groupId> <artifactId>Project-A</artifactId> <version>1.2.1</version> <scope>compile</scope> <optional>true</optional> </dependency> </dependencies> </project>Create a project for Optional Dependency
To see the effect of the <optional> tag, create a project that depends on project-with-optional.
<project> <artifactId>main-project</artifactId> <dependencies> <dependency> <groupId>org.geeksforgeeks.</groupId> <artifactId>project-with-optionals</artifactId> <version>5.1.1-SNAPSHOT</version> </dependency> </dependencies> </project>
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4