Difference between maven compiletime and runtime

Imagine you are deploying your application to a Java EE compliant server. The server provides all libraries implementing the Java EE standard, so you don't need to deploy them with your application.

During development, you will need the Java EE libraries with the compile time scope, since you need to compile the classes.

During the runtime however the dependencies are provided by the application server. Maven uses the 'provided' scope for such cases.


The following is taken from the maven documentation

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.

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.

So for example if we have the following two dependencies in our POM:

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging-api</artifactId>
    <version>1.1.3</version>
    <scope>compile</scope> <!-- can be ommitted as it is the default -->
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.3</version>
    <scope>runtime</scope>
</dependency>

Then the classes from commons-logging-api would be on the classpath during compilation of my module, whereas classes from commons-logging would not be available - if by accident I had a direct reference to a class from commons-logging in one of my project's classes then the build would fail.

However during runtime or test compilation & execution the classes from commons-logging would be on the classpath so could be used (i.e. by classes from commons-logging-api, or directly in tests of the project).

Both compile and runtime dependencies are included transitively (under the same scope) by Maven when your project is referenced as a dependency in another project.

p.s. As mentioned by kostja there is also the provided scope

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.

Basically the difference between provided and compile is that provided dependencies are not transitive.

Tags:

Maven