从0开始搭建一个属于自己的技术框架-2-搭建父子项目结构
开篇导读
上一篇:从0开始搭建一个属于自己的技术架构-1-新建一个Springboot项目
在上一篇文章中我简单介绍了如何利用maven创建一个Springboot项目,简单几步就可以随便一个简单的web。然而在实际情况中 ,一个项目中往往会有多个子项目或者子模块(没错,我说的就是现在还非常流行的微服务)。这种时候他们的项目打包和依赖管理就是一个问题了。我们需要统一各个模块的编译环境、依赖的版本,但是同时管理那么多模块的依赖版本是相当繁琐的事情,所以我们需要一个方法或者工具去解放程序猿的劳动力,令他们能更专注于Crtr c+ Ctrl v 算法设计和代码实现。Maven就提供了一个相当便利的方法。这篇文章主要介绍如何利用Maven创建一个父子项目。
目标
创建一个父子项目,跑起来之后访问相应的路径能返回Hello world。
准备
jdk1.8,能编译Java的IDE(Eclipse、MyEclipse、IntelliJ IDEA),maven环境
相关操作
新建一个空的maven项目
这个我就不详细说了。
新建一个module
这个是idea的操作,其他编译器请自行百度
在父项目的pom中添加子模块
<modules>
<module>system</module>
</modules>
<!-- 引入父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/>
</parent>
(idea会自动帮你加入相关的配置)
在子模块中添加父项目或者父模块信息
<parent>
<artifactId>Impossible</artifactId>
<groupId>impossible</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
(idea还是会自动帮你加入相关的配置)
在父项目的pom中加入依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<!-- 引入springboot单元测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
注意这里使用了<dependencyManagement></dependencyManagement>
这个标签,在子模块的依赖管理中非常重要,也是今天的主角。
在子模块的pom中加入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
注意这里没有使用<dependencyManagement></dependencyManagement>
在子模块创建你喜欢的目录结构并创建一个Springboot启动类
@ComponentScan(basePackages ="xxx.xxxx.xxxxx")
@SpringBootApplication
public class SystemApplication {
public static void main(String[] args){
SpringApplication.run(SystemApplication.class, args);
}
}
配置一下application.yml
server:
port: 8000
servlet:
context-path: /system
spring:
application:
name: system
写一个HelloController看看效果
@RestController
public class HelloController {
@RequestMapping("/hello")
public String Hello(){
System.out.println("Hello!");
return "Hello world";
}
}
Success
补充说明
<dependencyManagement>
</dependencyManagement>
在父项目pom的依赖外面加入dependencyManagement后,所有子项目再次引入dependencyManagement中的依赖时,默认会使用父项目的指定版本,当然也可以自己指定依赖版本。