Wednesday, April 6, 2016

Understand <optional>true</optional> in maven dependency

In pom's dependency , sometimes there's  <optional> true</option>. What does this mean? Why and when do you need to set this?

1. Meaning of <optional>

In short, if project D depend on project C, Project C optionally depend on project A, then project D do NOT depend on project A.

image

Since project C has 2 classes use some classes from project A and project B. Project C can not get compiled without dependencies on A and B. But these two classes are only optional features, which may not be used at all in project D, which depend on project C. So to make the final war/ejb package don't contain unnecessary dependencies, use <optional> to indicate the dependency is optional, be default will not be inherited by others.

What happens if project D really used OptionaFeatureOne in project C? Then in project D's pom, project A need to be explicitly declared in the dependencies section.

image

If optional feature one is used in project D, then project D's pom need to declare dependency on project A to pass compile. Also, the final war package of project D doesn't contain any class from project B, since feature 2 is now used.

2. Practical example

A practical example of using <optional> label is spring-boot-actuator. For example in spring-boot-actuator 1.3.3 release pom file, there are 20+ dependencies are optional, cause sprint-boot don't want to squeeze unnecessary jars into your final war package. Any project uses spring boot actuator will not have these 20+ jars in the final package by default. But if you do have want used some features, e.g. add a Timer metrics to meature the TPS of your web app, then you need to explicitely add dependency to metrics again.

image

3 comments:

  1. This is Great explanation!
    谢谢分享!! :)

    ReplyDelete
  2. Aweseome!! Really helped me!

    ReplyDelete
  3. well cooked, concise article well done!

    ReplyDelete

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List