lesson 4 自定义spring boot项目
上一篇我们已经了解到从IDE中创建一个springboot的项目,并对配置文件做出了调整。这次将会讲到自定义的spring boot项目将如何书写配置文件。
首先想好一个项目的名称,这里就叫做lesson吧,然后创建一个lesson的文件夹,并创建两个.gradle
后缀的文件,一个叫build.gradle
,另一个叫settings.gradle
。
在settings.gradle里写上
rootProject.name = 'lesson'
重点来了,要在build.gradle中写入内容了。
首先从spring的官网中找到spring io platform
项目,查看他的文档,找到关于gradle引入的片段,下面是spring官方文档中给出的内容
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'io.spring.gradle:dependency-management-plugin:1.0.0.RELEASE'
}
}
//plugins这段是我后面添加的
plugins {
id 'org.springframework.boot' version '2.1.2.RELEASE' //是项目引入spring boot gradle plugin
id 'java' //引入java插件,也表明这是java项目
}
apply plugin: 'io.spring.dependency-management'
repositories {
mavenCentral()
}
dependencyManagement {
imports {
mavenBom 'io.spring.platform:platform-bom:Cairo-SR6'
}
}
将这段内容复制进入咱们的build.gradle中。
除开我们自己添加的部分,其实这篇引入的内容已经可以满足最基本的springboot-WEB的使用了。
下面引入springboot的web和test依赖
dependencies{
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
注意:在新的版本中,用api
和implementation
来替换了原来的compile
,但compile也可以使用。
api和implementation两种依赖的不同点在于:它们声明的依赖其他模块是否能使用。
api:当其他模块依赖于此模块时,此模块使用api声明的依赖包是可以被其他模块使用
implementation:当其他模块依赖此模块时,此模块使用implementation声明的依赖包只限于模块内部使用,不允许其他模块使用。
完成之后,我们还需要添加一些调整。指定源码兼容版本,表名group
和version
,或者可选的指定源码包。
配置文件是如下这样:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'io.spring.gradle:dependency-management-plugin:1.0.0.RELEASE'
}
}
plugins {
id 'org.springframework.boot' version '2.1.2.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
//注意的是,这些配置一定要在 java插件之后
group 'com.lesson'
version '1.0.0'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencyManagement {
imports {
mavenBom 'io.spring.platform:platform-bom:Cairo-SR6'
}
}
dependencies{
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
可以使用命令行,或者IDE对其进行构建,当执行成功,则说明配置是没有问题的。
下面就去验证它是否有效。
项目中创建src/main/java
文件夹,创建包com.lesson.demo
,并创建一个Springboot的启动类LessonApplication.java
。
@SpringBootApplication
public class LessonApplication {
public static void main(String[] args) {
SpringApplication.run(LessonApplication.class, args);
}
}
最后直接启动,看到最后成功的日志,说明咱们自定义的springboot项目已经成功创建了。
在此基础上,还可以对项目配置文件进行精简,请各位小伙伴回忆上次的内容自己动动手吧。