1.前言
在Spring Boot 2.3.0版本之后,官方就将构建工具从Maven转为Gradle,主要的目的是加快项目的构建速度,因此我们这些普通“搬砖党”也不能落后呀,下面将从0开始搭建一个基于Gradle的分模块项目:
2.实验环境
JDK版本 | 11 |
SpringBoot版本 | |
Gradle版本 | 6.3 |
3.详细步骤
首先,需要明确,我们需要创建一个父模块,在这个父模块中又包含:rest,service,dao三个模块。
3.1 Step1
创建一个springboot项目,构建方式选择Gradle:
笔者这里使用了自己下载的Gradle,如果需要你也可以使用官方推荐的Gradle wrapper:
接下来创建各个子模块:
重复上述的步骤依次创建rest、service、dao,当然这个分层还是得按照具体的项目来,这里只是做一个简单的演示仅供参考;最后,不要忘记将一开始创建的src文件夹删除,得到下面的这个结果:
3.2 Step2
配置外层build.gradle:
buildscript {
ext {
springBootVersion = '2.3.2.RELEASE'
}
repositories {
mavenLocal()
maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
allprojects {
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'java-library'
group = 'com.ltx'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 11
targetCompatibility = 11
}
subprojects {
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
[compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8'
repositories {
mavenLocal()
maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
dependencies{
compileOnly 'org.projectlombok:lombok:1.18.8'
annotationProcessor 'org.projectlombok:lombok:1.18.8'
implementation 'org.codehaus.groovy:groovy'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
}
以及settings.gradle,将之前创建的3个模块包含进来:
rootProject.name = 'demo'
include 'dao'
include 'service'
include 'rest'
3.3 Step3
rest层配置:
buildscript {
ext {
springBootVersion = '2.3.2.RELEASE'
}
repositories {
mavenLocal()
maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
apply plugin: 'application'
mainClassName = 'com.ltx.rest.Application'
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
}
}
plugins {
id 'java'
id 'war'
}
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = '11'
targetCompatibility = '11'
repositories {
mavenLocal()
maven { url = 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
dependencies {
api (project(':service'))
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()
}
由于这里rest层需要引用service层,顾需要申明相关的依赖:
api (project(':service'))
于此同时,我们需要手动指定一下主启动类:
apply plugin: 'application'
mainClassName = 'com.ltx.rest.Application'
service、dao层亦如此。
3.4 Step4:
主启动类如下:
@SpringBootApplication
@ComponentScan(basePackages = {"com.ltx"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4. 结果
5.项目链接
安利一门超级好课!
扫码下单输优惠码【csdnfxzs】再减5元,比官网还便宜!