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?
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.
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.
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.
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.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With