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

What are the types of Maven dependency scopes? What are their use cases?

2月18日 21:34

Maven's dependency scope determines the validity of dependencies during different stages of the project, mainly including the following types:

  1. compile: Default scope, dependencies are valid during compilation, testing, and runtime. For example: spring-core, commons-lang3 and other core libraries.

  2. provided: Dependencies are valid during compilation and testing, but provided by the container or JDK at runtime. For example: servlet-api, jsp-api and other APIs provided by Web containers.

  3. runtime: Dependencies are valid during testing and runtime, but not needed during compilation. For example: JDBC drivers (such as mysql-connector-java), only the JDBC interface is needed during compilation.

  4. test: Dependencies are only valid during testing and will not be packaged into the final artifact. For example: JUnit, Mockito and other testing frameworks.

  5. system: Similar to provided, but requires explicit specification of local jar package paths, not recommended for use.

  6. import: Only used in dependencyManagement to import dependency management configurations from other POMs.

Dependency scope also affects dependency transitivity. For example, if A depends on B (scope=compile), and B depends on C (scope=test), then C will not be passed to A. Understanding dependency scope is important for avoiding class conflicts, reducing final package size, and improving build efficiency.

In actual projects, properly configuring dependency scope can avoid unnecessary dependency passing, reduce jar package conflicts, and optimize project structure. For example, configure Lombok as provided scope because it is only needed during compilation; configure logging implementations (such as logback) as runtime because only the logging interface is needed during compilation.

标签:Maven