一、准备工作
- IDE(IDEA或者Eclipse)
- Maven
二、创建新项目
使用IDE创建新的项目,选择Maven项目,这里不适用骨架
file->new-> project
选择maven及jdk版本
点击Next,输入账户名,存放路径,输入GroupId与ArtifactId
点击Finish完成创建;
三、编辑pom.xml
首先编辑pom文件,父级依赖及spring-web
启动器依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!--SpringBoot版本-->
<version>2.6.3</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
设置中选择本地maven的配置(不配置则使用idea默认配置)
导入依赖
四、添加Controller接口
在src>main>java下创建一个Controller包,创建一个HelloWorldController控制器
为控制器添加@RestController给Spring标明这是一个控制器,@RequestMapping("/test")接口路由
写一个方法,并添加@GetMapping("/hello")注解
package com.mansai.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author xiejw
* @version 1.0
* @date 2022/8/9 16:15
*/
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
}
五、添加服务启动类
- 添加
@SpringBootApplication
注解在类的上面 - 在main方法中加入
SpringApplication.run(SpringBootDemo.class,args);
至此,springBoot项目就搭建完成,点击启动就可以访问。默认使用8080端口package com.mansai; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author xiejw * @version 1.0 * @date 2022/8/9 16:19 */ @SpringBootApplication public class SpringStartApplication { public static void main(String[] args) { SpringApplication.run(SpringStartApplication.class,args); } }
- 浏览器访问 localhost:8080/test/hello
六.修改服务端口
在resources目录下添加Application.yml
server:
port: 8081
重启即可。
整体的目录结构如下: