文章目录
Spring Cloud(02)——搭建订单-支付微服务模块的父工程
在上一篇Spring Cloud(01)——初识Spring Cloud,回顾微服务及微服务架构中,我们初步了解了什么是SpringCloud和微服务,下面我们来先搭建一个rest微服务模块:订单(服务提供者)—支付(服务消费者)模块的父工程。
1、新建父工程项目空间
1、新建一个maven项目,注意选择自己的maven版本
2、设置字符集编码
3、注解激活生效
4、选择java版本为1.8
5、添加文件过滤File Types,选择不显示哪些文件(可选)
这里我添加了*.idea和 *.iml文件,再以后新建模块时,这两个文件将不会出现。
2、在父工程pom中添加依赖
<!--定义打包方式-->
<packaging>pom</packaging>
<!--统一jar包和版本号的管理 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<junit.version>4.12</junit.version>
<lombok.version>1.18.20</lombok.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.47</mysql.version>
<druid.version>1.1.16</druid.version>
</properties>
<!--子模块继承后,dependencyManagement提供的作用:依赖版本锁定,子模块不用写groupId和version-->
<dependencyManagement>
<dependencies>
<!-- springboot 2.2.2.RELEASE-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--springcloud Hoxton.SR1 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--spring-cloud-alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--日志和测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
3、Maven中DependencyManagement和Dependencies的区别
dependencyManagement是Maven中用来管理依赖版本号的方式,通常会在一个组织或者项目的最顶层的父POM看到dependencyManagement元素。
使用pom.xml中的dependencyManagement元素能让所有子项目引用一个依赖而不用显示的列出版本号。如:
<dependencies>
</dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
</dependencies>
这样做的好处是:如果有的个子项目都引用同一样依赖,则可以避免在每个使用的子项目里都声明一个版本号,这样当想升级或切换到另一个版本时,只需要在顶层父工程里更新,而不需要一个一个子项目的修改;另外如果某个子项目需要另外的版本,只需要声明version即可。
注意:
- dependencyManagement里只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用的依赖
- 如果不在子项目中声明依赖,是不会从父项目中继承下来的;只有在子项目中写了该依赖,才会从父项目中继续该项,并且version和scope都读取子父pom。
- 如果子项目中定义了版本号,那么会使用子项目中的版本。