关于SpringCloud版本说明和正确配置依赖传递介绍

1,085 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情

Sprnig Cloud 版本

Spring Cloud为开发人员提供了工具来快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器、智能路由、微代理、控制总线、一次性令牌、全局锁、领导选举、分布式会话、集群状态)。

SpringCloud依然是建立在SpringBoot基础之上的,所以在彼此版本上有必要的依赖关系,如下:

如何正确添加Spring-Cloud依赖

添加依赖

<properties>
    <spring.cloud-version>Hoxton.SR8</spring.cloud-version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring.cloud-version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

加入依赖组件

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    ...
</dependencies>

在使用Maven作为开发依赖管理工具时,很多时候版本和组件管理,会统一依赖父级pom.xml文件,那么在子项目中,如何正确添加对父级的依赖?

如何正确添加父级依赖

正常有两种方式可以添加对父级的依赖:

直接使用标签

<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.3.12.RELEASE</version>
   <relativePath/> <!-- lookup parent from repository -->
</parent>

这种方式添加依赖后,子模块会自动传递父级中的依赖,即父级中的依赖会自动传递到子模块中。

使用标签(建议)

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

这种方式添加的依赖后,子模块不会自动传递父级中的组件,需要手动添加。

实际上,第一种方式的内部也是采用的第二种方式,目前新版IDEA也改为了第二种。

解决Spring官网不稳定的方式

有时候创建项目时Spring官网很不稳定,可以使用阿里提供的地址:

阿里巴巴Archtype: start.aliyun.com/