Maven Dependency Scopes

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Background
    1. Compilation
    2. Testing
    3. Runtime
    4. Transitive Dependencies
  4. Scopes
  5. Summary

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 valueUsed During Build – CompilationUsed During Build – TestingAvailable In the Runtime ClasspathIncluded as Transitive Dependency, If ApplicableComments
compile (default)YYYYThe default scope, when omitted.
providedYYCan be looked up in the Maven repository during the build. Should be provided by the server used for the deployment when executing.
runtimeYYNot needed during compilation, but it is needed for runtime execution. Therefore, also included for test execution.
testYTest frameworks or libraries only used during testing.
systemYDEPRECATED – DO NOT USE: Similar to provided, but build configuration must provide a path to a jar file. Not looked up in the Maven repository. Also expects the systemPath element, such as:
<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.
Y – Yes
? – 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).

Maven Dependency Scopes

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.