Optional dependencies in Maven are used when a project cannot be split into sub-modules, and certain libraries are only needed for specific features. These dependencies are not included by default and must be explicitly added if required.
- Used for feature-specific dependencies
- Marked as optional in POM, not included automatically
- Users must redeclare them to use related functionality
Apply <optional> to Dependencies
We 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 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 tag
To 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>
- Now, when we try to reference an optional project from within the project, we discover that it does not exist. The <optional> tag precludes transitive inclusion.
- If we discover that we require an optional project in our main project, we simply designate it as a dependency.