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>

Optional Dependency in Maven

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.

Similar Reads

Apply to Dependencies

You can’t separate the producer project into submodules, you can apply to dependencies that enable additional behavior, as seen in the POM file below....

Use of the optional tag

To make a dependence optional, put the element to true in the declaration:...

Create a project for Optional Dependency

To see the effect of the tag, create a project that depends on project-with-optional....