Transitive Dependencies: requires transitive
You'll learn how requires transitive propagates dependencies automatically, making your module's required modules readable to your consumers.
The Problem: Shared Dependencies
Imagine module A requires module B, and B requires module C. By default, A cannot read C—it only has direct access to B. But what if B exposes types from C in its public API? Without access to C, code in A would fail to compile or run when using B's API.
This is where transitive dependencies solve the problem.
How requires transitive Works
When module B declares requires transitive C; instead of just requires C;, it tells the module system: "Anyone who reads me should also automatically read C."
Analogy: Think of it like a restaurant recommendation. If you trust your friend (module B) and they say "You must also meet the chef (module C) to appreciate this place," the chef becomes part of your experience automatically—transitive trust.
Syntax in module-info.java
// Module B
module com.example.moduleB {
requires transitive com.example.moduleC;
exports com.example.b;
}
Now any module that declares requires com.example.moduleB; will implicitly also read com.example.moduleC, without explicitly declaring it.
Why Use Transitive Dependencies?
Use requires transitive when:
- Your module's public API exposes types from another module
- Consumers of your module will need those types to compile and run
- You want to avoid forcing every consumer to manually add the same dependency
Without transitive, each consumer would need to explicitly require both B and C, creating maintenance burden and potential errors.
Key Takeaway: requires transitive creates implied readability, automatically making your dependencies available to your consumers—essential when your public API exposes types from other modules.