环境
JDK 1.8,maven3,springboot,IDEA
1. 使用maven方式手动构建SpringBoot第一个项目
(1)选择maven选项进行创建
(2)输入项目包、输入项目名称及位置(项目号与项目名称相同)
(3)项目结构
(4)增加SpringBoot相关的依赖(在pom.xml)
<!--引入springboot的父亲结类类的统一管理依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
</parent>
<!-- 增加一个web依赖-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
(5)创建一个主程序文件作为启动类
package com.juran;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//主程序入口
@SpringBootApplication
public class DomeApplication {
public static void main(String[] args) {
SpringApplication.run(DomeApplication.class,args);
}
}
(6)创建一个控制器返回请求数据
package com.juran.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //该 表明该类是一个控制器,返回的String类型的字符串
public class HelloController {
@GetMapping("hello")
public String Hello(){
return "this is my first SpringBoot Dome!";
}
}
(7)启动项目(主程序类中点击左侧运行按钮)并在浏览器中测试接口
2. 通过Spring initializr方式来构建SpringBoot 项目
(1)选择Spring initializr创建项目(该构建方式会自动产生主程序类,pom依赖将自动引入)
(2)目录结构
(3)创建控制器
package com.juran.springbdome;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("hello")
public String Hello(){
return "this is my first SpringBoot Dome!";
}
}
(4)测试效果
3.热部署及单元测试
单元测试
在程序的开发过程中,通过单元测试验证编写的功能模块或接口是否正确。
1、增加spring-boot-starter-test测试的依赖启动器,在pom.xml配置文件中增加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、编写控制器、单元测试类与测试方法
(1)控制器
@RestController
public class HelloController {
@GetMapping("hello")
public String Hello(){
return "this is my first SpringBoot Dome!";
}
}
(2)测试类及测试方法
@SpringBootTest //该类为测试类
public class DomeTest {
@Autowired //Spring依赖注入
HelloController helloController;
@Test //该方法为测试方法
void HelloTest(){
System.out.println(helloController.Hello());
}
}
(3)测试效果
注意:类前面通过注解为@Controller、@Service、@Configuration、@Repository,Spring框架就会自动生成bean对象,可以通过@Autowired注解自动注入,不需要用new创建对象。
热部署
一般情况下对一段业务代码修改以后,需要重新启动服务器,才能进行测试。热部署后不必重新启动应用服务程序,对修改的代码保存后就可以直接起作用,可以大大的提高我们的项目开发效率。
(1)增加Spring-boot-devtools热部署依赖包,在pom.xml文件中增加,更新依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
(2)IDEA工具热部署设置
文件--->构建、执行、部署--->编译器--->自动构建项目
(3)Maintenance窗口中配置
在任意界面中“Ctrl+Shift+Alt+/”--->注册表--->compiler.automake.allow.when.app.running(勾选)
(4)测试效果
运行程序后修改接口内容后ctrl+s保存,项目即可自动重新启动并部署,这就是热部署。