



本节创建一个Spring Boot项目,详细步骤如下:
(1)创建Maven项目。使用IntelliJ IDEA创建一个空的Maven项目,设置groupId和artifactId分别为com.onyx和springboot-demo,项目名称也会自动变为springboot-demo。
(2)添加Spring Boot的父依赖。本书使用的Spring Boot版本为2.3.10.RELEASE,添加依赖的pom.xml代码如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.10.RELEASE</version>
<relativePath/>
</parent>
<!--注意Java的版本,以自己的计算机安装的JDK为准-->
<properties>
<java.version>11</java.version>
</properties>
(3)新建包com.onyx.springbootdemo,在包下新建Spring Boot的启动类Springboot- DemoApplication,代码如下:
package com.onyx.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
注意,@SpringBootApplication标记本类是Spring Boot的启动类,执行这个类的main()方法即可启动Spring Boot项目。
(4)新建包com.onyx.springbootdemo.controller,在包下新建HelloController类。此处添加一个Web访问的入口,请求URL为“/hi”,使用@GetMapping表示请求方式是GET,@RestController表示本类是一个控制器(Controller)的入口类,其作用相当于@Controller+ @ResponseBody,且返回JSON数据。HelloController代码如下:
package com.onyx.springbootdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hi")
public String hi(){
return "success";
}
}
在pom.xml中添加Spring Boot的Web项目依赖(对Spring MVC的支持):
<!-- Spring MVC的依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Spring Boot的Maven构建插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
此时项目的目录结构如图2.1所示。
图2.1 Spring Boot项目的目录结构
(5)在IDEA中启动Spring Boot项目,即执行SpringbootDemoApplication中的main()方法,就能成功启动项目。打开浏览器,访问地址localhost:8080/hi,得到的返回结果如图2.2所示。
图2.2 Spring Boot项目的访问结果
至此,第1个Spring Boot项目搭建完成,并实现了对“/hi”地址的访问,开发人员可以从此迈入业务代码的开发阶段。