5

很多像spring这样的开源项目都包含多个模块,当在maven中添加这些模块作为依赖项时,我应该明确定义每个依赖项还是让传递依赖管理来做它的事情。例如,以下两种情况中的哪一种是最佳实践。

案例 1:包括我想要的最高级别的功能

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

案例 2:将框架的每个部分都包含为显式依赖项

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>
            .... other dependencies that are transitively resolved by maven
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.1.2.RELEASE</version>
    </dependency>

最佳实践案例 1 或案例 2 哪个是最佳实践,为什么?

4

2 回答 2

3

这取决于您是否声明了使用相同依赖项的任何其他依赖项(在本例中为 Spring)。如果您只需要顶级依赖项,请声明它。如果您使用的其他依赖项依赖于传递依赖项的特定版本,请将其声明为显式依赖项。

以 Spring 为例:如果您声明spring-webmvc然后决定需要另一个 spring 包,例如spring-security,明确定义它们都依赖的任何共享依赖项可能是个好主意,这样您就知道哪个版本包含在您的项目。

基本上,声明您需要特定版本的任何内容,然后让 maven 处理其余部分,直到您需要排除版本或声明特定版本。这就是构建 maven 的目的,所以让它管理依赖关系,直到它做出错误的决定。

于 2012-10-21T06:08:54.257 回答
1

我认为#1更好,因为从官方文档中可以清楚地看出这spring-webmvc取决于所有弹簧模块。

<!--
    Spring MVC for Servlet Environments (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Servlet Container such as Apache Tomcat (org.springframework.web.servlet.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>

您还可以查看pom以查看所有依赖项都spring-webmvc依赖于与它所在的版本相同的版本。

因此,至少对于这个用例,我认为不需要在您的 pom 中明确声明它们。

于 2012-10-21T06:22:34.127 回答