Optional Dependencies

This lesson explains how dependencies can be marked optional so that they are subsequently excluded as transitive dependencies.

Consider you are working on a project that requires custom parsing of JSON. Your colleague already has a jar artifact that can do what you are looking for, and under the hood it uses either Google’s Gson or Fasterxml’s Jackson libraries to parse JSON objects. Furthermore, a user can configure your colleague’s code to use one of two libraries when parsing JSON but not both. Say you decide to configure your colleague’s jar to use Jackson for parsing, but when you take the dependency on your colleague’s artifact, your project will still pull-in Google’s Gson artifacts even though your colleague’s code does not use Gson. This will cause your project size to bloat because of unused dependencies. Ideally, your colleague should have created two separate modules, one to be used for each JSON parsing library, but for some reason they didn’t. One solution is for your colleague to mark the dependencies on Gson and Jackson optional in their own project. That way, when you take a dependency on your colleague’s project, the two transitive dependencies will be omitted by Maven since they are marked optional. However, the onus of including the right dependency would then rest with the user, which is you. A pictorial representation of this setup is shown below:

Get hands-on with 1200+ tech skills courses.