Maven optional的作用
这里的optional
作用,可参考How do optional dependencies work?。
Project-A -> Project-B
The diagram above says that Project-A depends on Project-B. When A declares B as an optional dependency in its POM, this relationship remains unchanged. It's just like a normal build where Project-B will be added in Project-A's classpath.
Project-X -> Project-A
When another project (Project-X) declares Project-A as a dependency in its POM, the optional nature of the dependency takes effect. Project-B is not included in the classpath of Project-X. You need to declare it directly in the POM of Project X for B to be included in X's classpath.
简单来说,Project-X依赖Project-A,Project-A依赖Project-B,在Project-A中定义Project-B为optional的,在Project-X才会起作用并且不会引入Project-B依赖,也就是说Optional会阻止依赖传递。
比如有个项目X2,它的功能跟Hibernate类似,支持MySQL, PostgreSQL, Oracle,它会依赖各个数据库的驱动,在X2编译时,需要所有驱动的依赖;但你的项目仅使用其中一个数据库,而不需要其他依赖。X2中就可以声明所有驱动为Optional,你的项目直接声明依赖X2,X2中的驱动依赖并不会自动引入到类路径,你的项目需要显式声明目标数据库驱动依赖。