Skip to navigation

Maven Optional Dependencies: Keep Transitive Expectations Explicit

In short: Find which Maven dependencies are optional for consumers and where direct declarations must become explicit.

Published 20 min read
On this page

Direct answer

A Maven dependency marked optional is available to the project that declared it and is not propagated transitively to downstream consumers. The consumer question is therefore not “is this dependency in the graph” but “does my project use it directly, and if so, did I declare it”. Read your project’s imports and resolved classpath first, then write a consumer-facing declaration map that names every optional library you actually use. The concrete win is a build where each direct usage has a matching direct declaration. The concrete loss is that an undeclared optional dependency can compile today and break tomorrow when the upstream library changes, because nothing in your POM guaranteed its presence. The practical implication is that optional-usage auditing is a recurring check, not a one-time cleanup. Ask Claude Code to list which optional libraries your source imports and compare that list against the direct declarations in your POM.

Why an undeclared optional costs a release

Optional dependencies are a library author’s tool for saying “I can use this, but you may not need it”. That statement is about the library, not about your project. When your project imports a class from an optional library and does not declare it, the class arrives only because some other path in the dependency graph happens to bring it in.

The failure lands at the worst time. An upstream release changes its own optional handling, a dependency is excluded somewhere in the tree, or a conflict resolution drops the artifact, and your code stops compiling on a machine where it worked the day before. Nothing in your project model warned anyone, because the requirement was never yours.

Evidence and its limits

Official, F029: The Maven guide on optional dependencies and exclusions documents optional dependencies as available to the declaring project while not propagating transitively to downstream consumers. The Maven guides were not fetched in this pass, so verify the current wording and scope examples before drafting.

Official: The introduction to the dependency mechanism describes transitive resolution, scopes, and how the dependency tree is built.

Official: The POM reference documents the dependency element and its optional and scope settings.

Official: The Maven Enforcer Plugin documents rules that can enforce dependency constraints, including convergence, and is the standard reference for the enforcement discussion below.

Official, agent loop: Claude Code best practices recommends pairing an edit with a pass-or-fail check. For this audit the check is a resolved dependency list compared against imports.

Derived, F030: The consumer audit and declaration map below are an editorial method, not a universal scope or version recommendation.

No claim here depends on a Maven version number, a specific plugin release, or any benchmark.

What optional means in Maven

Optional is a flag on a dependency declaration in a producer’s POM. Setting it tells Maven that the artifact is needed to build and use the declaring project, but should not be inherited by consumers.

Declaration in the producer POM Present for the producer Present for the consumer by default Consumer sees it
Normal dependency Yes Yes, transitively In its tree
Optional dependency Yes No Only if the consumer declares it
Excluded by a consumer No No Never
Provided scope Compile-time only Per scope rules Depends on scope

Read the table as a routing rule. Anything optional in an upstream POM is a candidate for a direct declaration in yours, and the deciding evidence is whether your source imports it.

Read direct and transitive dependencies

Two commands produce the raw material for the audit. The dependency tree shows where each artifact came from. The effective POM shows what your project declares after inheritance and profile activation.

bash
mvn dependency:tree -Dverbose
bash
mvn help:effective-pom

The verbose tree marks omitted-for-conflict and omitted-for-duplicate entries, which is where an optional artifact that arrived by accident usually hides. Read the tree for the artifacts your source actually imports. Anything present in the tree but absent from your direct declarations is a candidate.

Resist the urge to declare every optional artifact the tree shows. An optional library your code never imports is not your requirement, and adding it makes the POM heavier for no benefit. The import search in the next section is the filter.

Map library consumers

Build the map one row per optional library that appears in the tree, with a column for whether your source uses it.

Optional library Present in tree via Imported by your source Direct declaration today Action
com.google.guava:guava com.vendor:sdk Yes, three classes No Declare directly
org.projectlombok:lombok inherited from parent Yes, annotations Yes, provided Keep
commons-io:commons-io transitive No No Leave undeclared
org.jetbrains:annotations transitive Yes, annotations No Declare directly

Two rows in this table are the defect the audit exists to find. guava and annotations are used and undeclared, so their presence depends on a transitive path your project does not control.

The import search is a source scan for the package roots of each candidate library. A hit in shipped code means the library is a requirement of your project, whatever the tree says about who brought it in.

Identify missing direct declarations

The gap list is the map filtered to rows where your source imports the library and no direct declaration exists. Each gap is a real risk, because the only thing keeping the build working is a transitive path.

For each gap, decide the scope from how your project uses the library. A library used at compile time and needed at runtime is a normal compile dependency. A library used only for annotations that do not affect bytecode can be provided. A library used only by tests belongs in the test scope. The POM reference documents the scope options.

Ask Claude Code to produce the gap list from the tree and the import scan, then to propose a scope for each gap with a reason. The Gradle variant attributes guide covers the neighboring JVM question of which artifact a consumer request selects.

Review scope and compatibility

Scope is a compatibility decision, and the wrong scope is its own defect. A library marked provided that your application actually needs at runtime fails on the server, not in the build. A library marked compile that only tests use inflates every consumer’s classpath.

Use pattern Appropriate scope Wrong scope symptom
Imported in shipped source, needed at runtime compile NoClassDefFoundError at runtime if provided
Annotation-only, no runtime effect provided Runtime classpath carries an unused jar
Used only in test source test Main artifact declares a test-only jar
Needed during build only compile or a dedicated build scope Missing at the phase that needs it

Dependency convergence is a related question and the Enforcer Plugin is the standard tool for enforcing it. Treat convergence enforcement as a build consistency rule, not as a security result. Two versions resolving to one does not make either version safe.

Document consumer requirements

The declaration map is the artifact that makes the audit durable. Keep it next to the POM, in the repository, with the evidence for each row.

A map that lives in a ticket is a map nobody reads during the next upgrade. The map that lives in the repo is what a new contributor checks before adding an import, and it is what a reviewer checks when an upstream library changes its optional handling.

The map should record the import evidence for each declared gap. A declaration added without evidence is a guess, and a guess that names a library your code does not use is scope inflation.

Explain the proposed POM change

A POM change is complete when a reviewer can answer four questions without running the build.

Question Where the answer lives Pass condition
Which gaps were found Declaration map Each row has import evidence
What scope each declaration uses POM diff Scope has a recorded reason
What the tree showed before Verbose tree excerpt Present in the change description
What the tree shows after Verbose tree excerpt Declarations appear as direct

Paste both tree excerpts into the pull request. A description that says “add missing dependencies” without the evidence forces the reviewer to reproduce the audit.

A worked walkthrough of one audit

Consider a project whose verbose dependency tree shows commons-io:commons-io arriving through two separate paths, neither of them a direct declaration. A source scan finds two imports from org.apache.commons.io in shipped code. That combination is the defect: the project uses the library and does not declare it, so its presence depends on transitive paths the project does not control.

The instinctive response is to leave it alone because the build is green. The problem is that green today is not green after an upstream change. A dependency update that alters one of those transitive paths, or an exclusion added elsewhere in the tree, removes the artifact and the project stops compiling on a machine where it worked the day before.

The fix is a direct declaration in the right scope.

bash
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.15.1</version>
</dependency>

Re-run the verbose tree after the change and confirm the artifact now appears as a direct edge. Compare the resolved version before and after: the version your declaration requests becomes authoritative for the conflict, which is a change in selection behavior worth stating in the change description rather than hiding.

Record the declaration in the consumer map with its import evidence. Two imports in shipped code is the reason the declaration exists, and that reason is what a reviewer checks during the next upgrade instead of re-running the scan.

Anti-patterns that look like audits

Four patterns recur around optional-dependency work, and each one hides a decision a reviewer needs to see.

Pattern What it looks like Why it hurts Do instead
Declaring everything in the tree Adding a declaration for every transitive artifact Scope inflation, heavier classpath Declare only what your source imports
Guessing a scope Marking a runtime library provided Fails at runtime, not at compile Match scope to actual usage
Treating convergence as safety Presenting one resolved version as a security win Convergence is consistency, not safety Frame it as a build consistency rule
Leaving the map in a ticket Recording the audit outside the repo Nobody reads it during the next upgrade Keep the map next to the POM

Scope guessing deserves the most caution. A library marked provided that the application needs at runtime produces a NoClassDefFoundError on the server, which is the failure furthest from the edit that caused it. The scope review is where that gets caught.

None of these is a Maven defect. They are review hazards, and the import scan plus the declaration map are what catch them.

A runbook for the next optional-usage question

The checklist earlier in this post is the pass condition. The runbook below is the sequence to follow when the question of missing declarations arises.

Run the verbose dependency tree and list every artifact present in the tree but absent from the direct declarations. This is the candidate set, and it is larger than the set you will act on.

Scan the source for imports from each candidate’s packages. A hit in shipped or test code means the library is your requirement. No hit means it is not yours, and declaring it would be scope inflation.

Decide the scope for each hit from how the project uses the library. Runtime imports want compile scope, annotation-only usage often wants provided, and test-only usage wants test scope.

Add the declarations and re-run the tree. Confirm each new declaration appears as a direct edge and note any resolved-version change the conflict now produces.

Record the gap list, the scopes, and the reasons in the consumer map next to the POM. The map is what turns this audit into a durable contract rather than a one-time cleanup.

The runbook takes minutes and produces the two artifacts a reviewer needs: the import evidence and the declaration map. Skipping it produces a POM change that reads as a guess.

Where this habit pays across the batch

The evidence-first habit in this post is the same one the rest of the batch applies to different constructs. Gradle constraints vs dependencies asks for a resolved-graph diff before a version change, Gradle capability conflicts asks for a component inventory before a resolution strategy, and Gradle variant attributes asks for the consumer request before a notation change.

The .NET posts apply the same discipline to package versions and generated code. NuGet central package management asks for a props and override inventory before centralizing, and .NET multi-targeting asks for a per-framework build before calling a version supported. C# source generators asks for the generator’s input change before reading its output.

The C++ posts apply it to configure inputs and dependency boundaries. CMake presets asks for the resolved preset inputs before a configure, CMake find_package vs FetchContent asks for a resolution trace before choosing a path, and Conan CMakeDeps asks for the target contract before a layout change.

That consistency is deliberate. The constructs differ, but the shape is the same: read the evidence the tool already produces, then make the smallest change the evidence supports.

The same shape extends to the ecosystems covered in earlier batches. On the Python side, dependency groups versus extras separates local workflow requirements from published optional features, and stub drift audits a package’s declared types against its documented runtime surface. TypedDict boundaries covers separating truly optional keys from missing data before replacing broad dictionary annotations.

On the Go side, module compatibility covers keeping an exported API change inside an import contract, and graph pruning covers why an indirect dependency entry is graph metadata rather than something to delete. Workspace boundaries covers deciding what belongs in go.work versus what stays a module requirement.

On the Rust side, feature unification covers mapping which optional APIs a workspace build actually exposes, and workspace inheritance covers centralizing metadata without hiding crate-local exceptions. Profile boundaries covers separating diagnostic and optimization settings from options that change observable program behavior.

Optional-dependency handling has a direct analog in Python dependency groups versus extras, where the same “which requirements reach a consumer” question applies to packaging metadata rather than transitive propagation. Both are consumer-contract questions, and both reward an import scan before a declaration.

Working alongside the review bottleneck

A declaration change with import evidence pasted in is cheap to review. A change described as “added the missing dependency” is a reviewer reproducing the work, and reproduction is the expensive part. The Claude Code code review bottleneck covers what happens when generation outpaces the review that has to accept it.

The same reasoning appears in Claude Code cost per verified change, which treats verified work as a separate unit from generated output. An import scan is a verified unit. A “trust me, it was missing” description is not.

When the review queue is long enough that verification slips, the failure mode is a merge that nobody actually checked. Prevent false success from passing tests covers the case where a green build is the only evidence, and an undeclared optional is exactly the case where green proves less than it appears to.

The concrete win, loss, and implication

The concrete win is a POM where every direct usage has a direct declaration. An upgrade that changes upstream optional handling stops being a surprise, because the libraries your source imports are requirements your project states for itself.

The concrete loss is maintenance. Direct declarations are a commitment: each one is a version your project now manages, and each scope decision is a claim about runtime behavior that can be wrong. A project that over-declares to be safe pays for it in a heavier classpath and more version conflicts to resolve.

The practical implication is that the consumer side of optional dependencies is a contract you owe yourself. Teams that keep the declaration map resolve fewer “why did this stop compiling” incidents. Teams that rely on the tree spend a release cycle discovering which transitive paths were load-bearing.

The JVM posts in this batch cover the neighboring questions. Gradle constraints vs dependencies covers version policy without adding a graph edge. Gradle capability conflicts covers two components claiming one capability, and Gradle variant attributes covers consumer-to-producer matching.

For the .NET side of dependency ownership, NuGet central package management covers which central version wins, and .NET multi-targeting covers per-framework package versions.

Supply-chain questions sit adjacent to dependency declarations but outside this post. The Claude Code hallucinated packages guide covers blocking a nonexistent dependency, and the Claude Code dependency install side effects guide covers install-time behavior.

Review habits sit upstream of every POM change. Ask what Claude Code verification requires before calling the audit done, and Claude Code cost per verified change treats verified work as a separate unit from generated output.

Evidence map showing an optional dependency present for its declaring project but not propagated transitively, leaving the consumer to declare it directly.
Editorial evidence map based on F029 and F030. An optional dependency does not travel to consumers by default; labels are the post author’s.

Checklist before merging an optional-dependency audit

Run this list against the diff. Each row is a pass condition.

Check Pass condition If it fails
Declaration map Every gap has import evidence Complete the import scan
Scope per gap Recorded reason for each scope Justify or change the scope
Before tree Verbose tree excerpt recorded Run the tree task
After tree Declarations appear as direct Re-run the tree task
Convergence Not presented as a security result Reframe the claim
Over-declaration No library added without a hit Remove the unused declaration
Workflow from a verbose dependency tree and import scan, through a declaration map, to direct POM declarations verified by a second tree run.
Editorial workflow derived from F029 and F030. The sequence describes a review routine; it does not prescribe a scope for every project.

Working with Claude Code on the audit

Give the agent the module POM and the source root. Ask for the verbose dependency tree and an import scan for each optional artifact the tree shows, before any POM edit. The agent session works best when the check is a pass-or-fail comparison, which is the shape the official best-practices guidance recommends.

Ask the agent to report four things when it finishes. The gap list with import evidence. The proposed scope and reason for each gap. The before-tree excerpt. The after-tree excerpt showing the declarations as direct. A report that omits the import evidence has not finished, because a declaration added without a hit is scope inflation.

Reviewing scope is the reviewer’s job. The agent reads the POM and can run Maven, but deciding how your project uses a library is a design decision. The Claude Code verification guide covers the review questions: what changed, what proves it, and what was not checked.

Tradeoff between direct declarations that remove reliance on transitive paths and the version-management burden each added declaration carries.
Editorial tradeoff diagram based on F029 and F030. Direct declarations remove a surprise at the price of an owned version.

Data gap and future update

F029 rests on Maven guides that were not fetched in the research pass, so the current wording and scope examples should be rechecked against the Maven documentation before a real change. A future update should record, per project, which upstream libraries declare optional dependencies your code uses, and the Maven version the observations were taken at.

No benchmark, build-time measurement, or security claim is made here. The effect of a declaration on build duration or supply-chain risk is out of scope.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. It is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route, or read the quickstart for the request shape.

FAQ

Does an optional dependency disappear from every graph?

No. It is absent from a consumer’s tree by default because it is not propagated transitively. It is present in the declaring project’s own build, and it appears in a consumer’s tree the moment that consumer declares it directly.

How do I know if my project needs to declare one?

Search your source for imports from the library’s packages. A hit in shipped or test code that your project relies on means the library is your requirement, and the declaration map records the evidence.

Does marking a dependency optional in my own POM affect my consumers?

Yes. Setting optional on your own declaration tells Maven not to propagate it transitively. Consumers who need the library declare it themselves, which is the behavior the Maven guide documents in F029.

Does dependency convergence make my build secure?

No. Convergence means versions agree across the tree, which is a consistency property. It does not evaluate the safety of the selected version. Treat the Enforcer Plugin’s convergence rule as a build consistency check.

What scope should a declared optional dependency use?

Match the scope to how your project uses the library. Runtime imports want compile scope, annotation-only usage often wants provided, and test-only usage wants test scope. The scope reference in the POM documentation covers the options.

This post is one of ten build-system and dependency guides written together. Gradle Constraints vs Dependencies, Gradle Capability Conflicts, and Gradle Variant Attributes cover the three neighboring JVM resolution questions.

The .NET posts cover version and generated-code boundaries: NuGet Central Package Management, .NET Multi-Targeting, and C# Source Generators.

The C++ posts cover build inputs and dependency boundaries: CMake Presets, CMake find_package vs FetchContent, and Conan CMakeDeps.

More from this batch

More Claude Code troubleshooting

Sources

Control checklist covering the declaration map, import evidence, scope reason, and before and after dependency tree excerpts.
Editorial control checklist derived from F029 and F030. Passing it shows the audit was evidenced; it does not make the selected versions safe.
Verdict that an audited consumer declares each optional library it imports directly, removing reliance on transitive paths it does not control.
Editorial verdict based on F029 and F030. Direct declarations backed by import evidence are the consumer’s own contract.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →