문제

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.
도움이 되었습니까?

해결책

This was reported as MNG-1630. Although closed as 'Fixed', a comment suggests:

Actually, this issue was never fixed. The changes that have been committed in r354544 are insufficient as they neither update the DefaultArtifactCollector nor the DefaultModelDefaultsInjector to propage the optional flag from a managed dependency/artifact to a project dependency.

You've now opened a duplicate of this issue (MNG-5632) requesting either a behavioural or documentation change, which seems like an ideal way to track this.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top