Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "optional" dependencies and when to use "provided" scope?

Dependencies decorated by <optional>true</optional> or <scope>provided</scope> will be ignored when they are dependent transitively. I have read this, my understanding is like the difference between @Component and @Service in Spring, they only vary semantically.

Is it right?

like image 563
qining.shi Avatar asked Nov 03 '16 02:11

qining.shi


People also ask

What is the use of provided scope in Maven dependency?

Provided. We use this scope to mark dependencies that should be provided at runtime by JDK or a container. A good use case for this scope would be a web application deployed in some container, where the container already provides some libraries itself.

What are optional dependencies?

Optional dependencies are used when it's not possible (for whatever reason) to split a project into sub-modules. The idea is that some of the dependencies are only used for certain features in the project and will not be needed if that feature isn't used.

Which is used to avoid optional dependency?

In order to exclude these special dependencies from the main project, we can apply Maven's <optional> tag to them. This forces any user who wants to use those dependencies to declare them explicitly. However, it does not force those dependencies into a project that doesn't need them.

What is scope provided in POM xml?

The <scope> element can take 6 values: 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. This is the default scope, used if none is specified.


1 Answers

In addition to the comment, there is more important semantic difference: "Provided" dependencies are expected to be supplied by the container, so if your container gives you hibernate, you should mark hibernate as provided.

Optional dependencies are mainly used to reduce the transitive burden of some libraries. For example: If you can use a library with 5 different database types, but you usually only require one, you can mark the library-dependent dependencies as optional, so that the user can supply the one they actually use. If you don't do, you might get two types of problems:

  1. The library pulls a huge load of transitive dependencies of which you actually need very few so that you blow up your project without reason.

  2. More dangerously: You might pull two libraries with overlapping classes, so that the class loader cannot load both of them. This might lead to unexpected behaviour of your library.

like image 112
J Fabian Meier Avatar answered Oct 20 '22 06:10

J Fabian Meier