I am a bit confused about how the mechanism for optional dependencies works in Maven.
Is seems optional dependencies only work when specified directly, and not via Dependency Management.
I created three test projects p1-p3, with dependencies:
- p3 depends on p2
- p2 depends on p1
If I declare a dependency as optional in the <dependencies>
element, this works as expected. POM of p2:
<dependencies>
<dependency>
<groupId>testgroup</groupId>
<artifactId>p1</artifactId>
<version>1.0-SNAPSHOT</version>
<optional>true</optional>
</dependency>
</dependencies>
Result: The build of p3 pulls in p2, but not p1.
However, if I If I declare a dependency as optional in the <dependencyManagement>
element, it seems to be ignored. POM of p2:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>testgroup</groupId>
<artifactId>p1</artifactId>
<version>1.0-SNAPSHOT</version>
<optional>true</optional>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>testgroup</groupId>
<artifactId>p1</artifactId>
</dependency>
</dependencies>
Result: The build of p3 pulls in p2 and p1.
Is this expected behavior? I could not find this documented anywhere.
Notes:
- Tested with Maven 3.0.3 and 3.2.1.
- To see whether the build of p3 used p1, I checked both the output of
mvn dependency:tree
, and the classpaths listed by mvn -X
(with identical results).
- I also tried putting the
<dependencyManagement>
element into the POM of p1, instead of p2. The result was the same, i.e. <optional>
had no effect.