文档
https://spring.io/guides/gs/multi-module/
插件传递
创建SpringBoot项目需要两个插件, 在根项目中声明:
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
如果子项目需要Spring框架, 那么应该从根项目传递插件, 再使用起步依赖: (否则无法从根项目构建, 类路径中插件重复)
// 同样在根项目的配置文件build.gradle声明
project(':MySpringBoot') {
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
}
dependencies {
implementation project('MySpringBoot')
}
根项目完整配置:
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'io.spring.dependency-management' version '1.0.10.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
implementation project('MySpringBoot')
}
test {
useJUnitPlatform()
}
// childprojects { // 为所有子项目应用
project(':MySpringBoot') {
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
}
SpringBoot类库子项目的配置文件build.grade:
plugins {
id 'java-library'
}
group = 'com.githmb.spring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
bootJar {
enabled = false
}
jar {
enabled = true
}
缺陷
子项目无法单独测试, 需要从根项目启动子项目的测试任务:
kasumi@kasumi-VirtualBox:~/IdeaProjects/MySpring$ gradle test
BUILD SUCCESSFUL in 2s
9 actionable tasks: 9 up-to-date
kasumi@kasumi-VirtualBox:~/IdeaProjects/MySpring$ gradle :MySpringBoot:test
BUILD SUCCESSFUL in 1s
4 actionable tasks: 4 up-to-date
多模块正确的打开方式
首先,应该有一个不含任何业务逻辑代码的根项目,再创建Application和Library等系列子模块,方便管理子项目,并且保持项目之间的独立性.
什么是独立性? 独立可测试,可被其它项目引用向外部提供接口.
根目录应该具有重大的决策权,不修改子模块就可作决策.
参考该项目:
https://github.com/develon2015/MultiModule