How provided scope version works in mavan

Viewed 607

I know when provided scope define for any maven dependency ,it will provided by web server or runtime environment. But not sure how version can help here.

Take an example

<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>eclipselink</artifactId>
    <version>2.6.4</version>
    <scope>provided</scope>
</dependency>

In compile, it will use eclipselink version 2.6.4 but in runtime what will be it? Is it solely depends on the provider of the dependency while bundling it or it will depend on any other factor?

If it solely depends on the provider then what is the purpose of defining the version in provided scope? Or while defining provided scope version we should be cognizant of web server bundle version?

2 Answers

The version is to let Maven know which version of dependency should it uses when compiling the codes during packaging WAR/JAR/EAR etc.

The provided scoped is to let Maven know if it needs to include this dependency into WAR/JAR/EAR . If it is provided scoped, does not include. Otherwise , include it.

Maven will not know the version of the dependencies in your runtime environment (i.e application server) . It is the developers' responsibility to match the version specified in pom.xml to the version of the dependency of the runtime environment manually. Otherwise , you could end up with the situation like the application can actually run in the runtime environment , but since you specify a older version in pom.xml which causes you fail to package the application due to the older version does not contain the new feature classes that were introduced in the newer version.

From official documentation:

This is much like compile (Compile dependencies are available in all classpaths of a project.), 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. A dependency with this scope is added to the classpath used for compilation and test, but not the runtime classpath. It is not transitive.

You have to specify a version, so that at compile time Maven knows which version of the library to bring in and compile (and run tests) against. But after that, the dependency is no longer used. It is assumed the runtime environment will make this dependency available on the classpath.

You have to know what version your runtime environment is going to provide, and you want to compile against that same version. If you do not, your application could behave unexpectedly, or even crash with runtime exception(s).

Related