Table of Contents
Introduction
When adding dependencies in a Maven build, every dependency has a scope, which controls how it is consumed.
<dependency>
<groupId>somegroupid</groupId>
<artifactId>someartifactid</artifactId>
<version>1.0</version>
<scope>scopevaluegoeshere</scope>
</dependency>
Background
To make sure we understand Maven scopes, let’s discuss some related terms:
Compilation
Compilation is when the Maven build for this project uses the Java compiler to create byte code from the application’s Java source code.
Testing
A Maven build for a project has 2 possible testing phases within that project’s build lifecycle:
- Unit Testing
- Integration Testing
Runtime
This is the behavior used when this Java project is being executed.
Transitive Dependencies
If this Java project is a dependency in another Java project, then certain dependencies may be carried forward as transitive dependencies in that second project. Just by including this Java project as a dependency, then transitive dependencies are also implicitly included.
Scopes
Maven dependencies can carry the following scope values:
| Scope value | Used During Build – Compilation | Used During Build – Testing | Available In the Runtime Classpath | Included as Transitive Dependency, If Applicable | Comments |
|---|---|---|---|---|---|
| compile (default) | Y | Y | Y | Y | The default scope, when omitted. |
| provided | Y | Y | Can be looked up in the Maven repository during the build. Should be provided by the server used for the deployment when executing. | ||
| runtime | Y | Y | Not needed during compilation, but it is needed for runtime execution. Therefore, also included for test execution. | ||
| test | Y | Test frameworks or libraries only used during testing. | |||
<systemPath>${java.home}/../lib/tools.jar</systemPath> | |||||
| import | ? | ? | ? | ? | Used for importing other poms, often called Bill of Material (BOM) poms. Not directly transitive, but imported dependencies from that pom may be. |
? – Depends upon the scope of the imported dependencies inside of the imported pom.
Summary
Maven dependencies can be controlled with a scope value, indicating how they should be used in this Java project’s build and whether or not they should be included in any projects that depend upon this project (AKA as a transitive dependency).
Leave a comment