Can a program depend on a library during compilation but not runtime?

前端 未结 10 1802
深忆病人
深忆病人 2020-11-30 18:18

I understand the difference between runtime and compile-time and how to differentiate between the two, but I just don\'t see the need to make a distinction between compile-t

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 18:21

    Each Maven dependency has a scope that defines which classpath that dependency is available on.

    When you create a JAR for a project, dependencies are not bundled with the generated artifact; they are used only for compilation. (However, you can still make maven include the dependencies in the built jar, see: Including dependencies in a jar with Maven)

    When you use Maven to create a WAR or an EAR file, you can configure Maven to bundle dependencies with the generated artifact, and you can also configure it to exclude certain dependencies from the WAR file using the provided scope.

    The most common scope — Compile Scope — indicates that the dependency is available to your project on the compile classpath, the unit test compile and execution classpaths, and the eventual runtime classpath when you execute your application. In a Java EE web application, this means the dependency is copied into your deployed application. In a .jar file however, dependencies will not be included with compile scope..

    Runtime Scope indicates that the dependency is available to your project on the unit test execution and runtime execution classpaths, but unlike compile scope it is not available when you compile your application or its unit tests. A Runtime Dependency is copied into your deployed application, but it is not available during compilation! This is good for making sure you do not mistakenly depend on a specific library.

    Finally, Provided Scope indicates that the container in which your application executes provides the dependency on your behalf. In a Java EE application, this means the dependency is already on the Servlet container’s or application server’s classpath and is not copied into your deployed application. It also means that you need this dependency for compiling your project.

提交回复
热议问题