Maven dependency within dependency with different scope

后端 未结 4 1745
深忆病人
深忆病人 2020-12-16 15:19

Say I have two Maven dependencies defined in a project like below.

    
        com.thoughtworks.xstream
            


        
4条回答
  •  执笔经年
    2020-12-16 15:31

    As mattb's answer says, declaring the dependency as test scope overrides the transitive compile-scoped dependency declaration, and as a result the dependency is not included in your packaged war.

    If you only need the dependency in your tests because 'mylibrary' needs it to execute, you shouldn't declare the dependency at all in your project's pom. Let the transitive dependency resolution process handle it.

    If your project does use the xstream jar directly, you can still rely on the transitive dependency, as you will need a compatible version for your project and 'mylibrary' to both run against the xstream jar. You should have unit tests that exercise the functionality, and if mylibrary changes version of xstream to an incompatible version, your builds should fail, and you can address the issue at that point.

    In general I'd say you should try to avoid declaring dependency versions directly in multi-module projects. I declare the versions in a dependencyManagement section of a parent POM so that the child need only declare the groupId/artifactId. Alternatively, from Maven 2.0.9 onwards there is an additional dependency scope of import:

    This scope is only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM's section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

    So using import scope you can define your common dependency versions in a single POM, import the dependencies of that POM into your dependencyManagement section, and just declare the groupId/artifactId of the dependency in your other POMs.

提交回复
热议问题