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

What is < scope > under < dependency > in pom.xml for?

1个答案

1

In Maven projects, the pom.xml file serves as a core configuration file containing all project configuration details, including dependencies. The <scope> element within the <dependency> tag defines the dependency's scope, indicating its visibility and inclusion across different project phases (such as compilation, testing, and runtime).

  1. compile: This is the default scope, meaning the dependency is used in all phases, including compilation and runtime. Compilation dependencies are included in the default classpath and are also packaged.

  2. provided: Indicates that the dependency is required during compilation and testing phases but not during runtime, as it is provided by the runtime environment. Typical examples include Servlet API and JNDI API, which are supplied by Java EE containers at runtime.

  3. runtime: Indicates that the dependency is required during runtime and testing phases but not during the compilation of main source code. For example, JDBC driver implementations.

  4. test: Indicates that the dependency is used exclusively during the testing phase for compiling and executing test code. It is not utilized during normal runtime or compilation.

  5. system: Similar to provided, but requires manually specifying the path to the JAR file. It is not retrieved from Maven repositories but from a fixed local system path.

  6. import: This scope is typically used within <dependencyManagement> to import dependency configurations from other projects.

For example, if you have a web application, you might configure the Servlet API in your pom.xml as follows:

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

Here, provided is used because Java EE containers (such as Tomcat) typically provide the implementation of the Servlet API, so the dependency is not needed at runtime. This reduces the size of the built package and avoids potential conflicts.

2024年8月15日 18:16 回复

你的答案