In Maven, the <scope>
element within the <dependency>
tag is used to specify the visibility of a dependency, relative to the different lifecycle phases (like compile, test, runtime). The scope also determines if the dependent libraries are packaged with the application or not.
Here are the different scopes available in Maven:
-
compile
(Default Scope)
- The dependency is available in all classpaths of a project.
- It's required for normal use of the application, and it's available at compile time, test time, and runtime.
- If you don't specify a scope, then
compile
is the default.
-
provided
- Used to indicate that the JDK or a container will provide the dependency at runtime.
- This is much like
compile
, but indicates you expect the JDK or a container to provide the dependency at runtime.
- Example: Building web apps that will be run on a server which provides the Servlet API.
-
runtime
- The dependency is not required for compilation but is for execution.
- It indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
- Example: JDBC drivers.
-
test
- The dependency is available only for the test compilation and execution phases.
- The library is used for testing purposes, which includes running and compiling the tests.
- These dependencies aren't included during the packaging of the application.
-
system
- You have to provide the system path to the library.
- Indicates that you have to provide the system path of this dependency. It's always available and is not looked up in a repository.
- It's similar to
provided
, but you must also specify the location using the <systemPath>
element.
import
(Only used with Dependency Type of pom
in <dependencyManagement>
)
- This scope is used on a dependency of type
pom
in the <dependencyManagement>
section. It indicates that the specified POM should be replaced with the dependencies in that POM's <dependencyManagement>
section.
- This scope is especially useful when you have a set of projects that inherit a common parent and you want to ensure that they all use the same version of a particular dependency.
Always choose the appropriate scope based on the real needs of the dependency in your project. This ensures that your application only packages what it truly requires and avoids potential runtime conflicts.