目录
简介
项目需求
实现步骤
1. 新建 springboot-parent 父级项目,项目结构如图
2. 在 pom 文件添加如下配置
3. 在父级项目 springboot-parent 右键新建 Maven module 选项,创建子模块 springboot-service,项目结构如图
4. 在 pom.xml 配置文件中添加如下配置
5. 在父级项目 springboot-parent 右键新建 Maven module 选项,创建子模块 springboot-controller,项目结构如图
6. 在 pom,xml 配置文件中添加如下配置
7. 分别在 springboot-service,springboot-controller 添加对应方法
总结
前面介绍的项目都是一个整体的 SpringBoot 项目,在实际的开发过程中,特别是微服务部分,经常需要将各个功能模块分开,使用 Maven 就能很好的实现这个效果
搭建一个 springboot-parent 父级项目,搭建 springboot-controller,springboot-service 分模块
依赖关系
↗ springboot-controller(子)
springboot-parent(父) ↓↘ springboot-service(子)
com.ibm.spring
springboot-parent
0.0.1-SNAPSHOT
pom
springboot-parent
http://maven.apache.org
org.springframework.boot spring-boot-starter-parent 2.0.6.RELEASE
UTF-8 UTF-8 1.8 0.0.1-SNAPSHOT 0.0.1-SNAPSHOT
springboot-controller springboot-service
org.springframework.boot spring-boot-starter-web
com.ibm.springboot springboot-controller ${module.controller.version} com.ibm.springboot springboot-service ${module.service.version}
org.springframework.boot spring-boot-maven-plugin
注意:
(1) 对于父级项目,packaging 应设置成 pom 格式,否则无法添加子模块
(2) 上面配置中加粗部分实际上应该是后面两个子模块创建完毕后根据子模块信息添加
com.ibm.spring springboot-parent 0.0.1-SNAPSHOT
com.ibm.springboot
springboot-service
jar
UTF-8
com.ibm.spring springboot-parent 0.0.1-SNAPSHOT
springboot-controller
springboot-controller
jar
UTF-8
com.ibm.springboot springboot-service
注意:Controller 模块需调用 Service 模块,所以在 springboot-controller 子模块中要添加 springboot-service 依赖
springboot-service
@Service
public class TestService {public String getMessage() {return "test message";}
}
springboot-controller
@RestController
@RequestMapping("/test")
public class TestController {@Resourceprivate TestService testService;@GetMapping("/msg")public String getMessageFromService() {return testService.getMessage();}
}
1. 父级项目添加子模块的配置有两处,分别在
2. 由于 Controller 模块还作为启动模块,特别要主要各个模块之间的包名的关系
如果 Controller 模块的启动类 App.class 所在的包和 Service 层所在的包名不匹配,则需要在启动类上添加 @ComponentScan 或 @ComponentScans 注解添加要扫描的包的路径;最佳实践:Controller 层的启动包名应是其他被调用子模块包名的父级关系(包含关系)。