乐闻世界logo
搜索文章和话题

What is the difference between maven scope compile and provided for JAR packaging

1个答案

1

In Maven, dependency management is a core feature, and scope defines how dependencies interact with the project. Specifically, the compile scope and provided scope are two common dependency configurations that behave differently during JAR packaging.

Compile Scope

Definition:

The compile scope is the default scope for Maven dependencies. If no scope is specified for a dependency, it defaults to compile scope.

Characteristics:

Dependencies are available in all classpaths, including compilation, test, and runtime paths. When the project is packaged into a JAR file, these dependencies are included.

Example:

If your project depends on the commons-lang3 library, you typically need to use its functionality during compilation, testing, and runtime. Therefore, you would set it to compile scope:

xml
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> <scope>compile</scope> </dependency>

Provided Scope

Definition:

The provided scope marks dependencies required during compilation and testing but not during runtime, as they are provided by the JDK or container at runtime.

Characteristics:

Dependencies are available during compilation and testing but are excluded from the packaged JAR file. This scope is commonly used for dependencies that rely on container runtime or JDK-provided libraries, such as the Servlet API.

Example:

When developing a web application, you might use the servlet-api library for compilation and testing, but at runtime, the Servlet container (e.g., Tomcat) provides this library:

xml
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>

Summary

In summary, the compile scope applies to libraries required at runtime, while the provided scope applies to libraries provided by the environment (e.g., container or JDK) at runtime. Correctly using both scopes ensures the project's buildability and testability, and effectively controls the size of the final deployment package by excluding unnecessary libraries. This is especially important when maintaining large projects or optimizing application deployment.

2024年8月15日 17:52 回复

你的答案