当工件构建为JAR时,maven范围编译和提供之间的区别是什么?如果它是WAR,我能理解-工件将包含或不包含在WEB-INF/lib中。但是对于JAR来说,这并不重要——依赖关系不包括在内。当它们的作用域被编译或提供时,它们必须在类路径上。我知道所提供的依赖关系不是可传递的——但这仅仅是一个区别吗?


来自Maven Doc:

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.

回顾:

依赖关系是不可传递的(正如你所提到的) 提供的作用域只在编译和测试类路径上可用,而编译作用域在所有类路径上可用。 所提供的依赖项没有打包

如果您计划生成一个包含其所有依赖项的JAR文件(典型的xxxx-all.jar),那么提供的范围很重要,因为这个范围内的类不会打包到生成的JAR中。

更多信息请参见maven-assembly-plugin

Compile means that you need the JAR for compiling and running the app. For a web application, as an example, the JAR will be placed in the WEB-INF/lib directory. Provided means that you need the JAR for compiling, but at run time there is already a JAR provided by the environment so you don't need it packaged with your app. For a web app, this means that the JAR file will not be placed into the WEB-INF/lib directory. For a web app, if the app server already provides the JAR (or its functionality), then use "provided" otherwise use "compile".

这是参考资料。

编译

在类路径中可用,如果是普通jar,不要将此依赖项添加到final jar;但是如果最终的jar是一个单独的jar(例如,可执行的jar),则将这个jar添加到jar中。

提供

依赖项将在运行时环境中可用,所以在任何情况下都不要添加此依赖项;甚至不是在单个jar(即可执行jar等)中

对于jar文件,区别在于MANIFEST中列出的类路径。如果在maven-jar-plugin配置中将addClassPath设置为true,则jar中包含MF文件。'compile'依赖项将出现在清单中,'provided'依赖项不会出现。

我最讨厌的是这两个词的时态相同。要么编译并提供,要么编译并提供。

如果jar文件类似于可执行的spring启动jar文件,那么所有依赖关系的范围必须编译为包括所有jar文件。

但如果jar文件用于其他包或应用程序,则不需要在jar文件中包含所有依赖项,因为这些包或应用程序本身可以提供其他依赖项。