scope引起的问题

时间:2022-04-23
本文章向大家介绍scope引起的问题,主要内容包括背景、解决方法、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

背景

执行mvn clean test命令提示部分包不存在,但通过eclipse的clean操作后可以执行mvn test命令

解决方法

mvn clean操作为清空编译的class文件,test的话,会去编译test相关的文件,并执行test

根据日志提示发现,提示不存在的包,都是在pom.xml中加了<scope>test</scope>的

官方解释:

The <scope> element can take 6 value: compile, provided, runtime, test, system and import.

This scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.

compile This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects. provided This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive. runtime This scope 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. test This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. system This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository. import (only available in Maven 2.0.9 or later) This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

加入了<scope>test</scope>的话,包只在编译test部分和执行,而该包在非测试部分也需要引入,所以报错,提示包不存在,所以去掉<scope>即可