1、创建 Spring Boot 项目
Intellij IDEA 一般可以通过两种方式创建 Spring Boot 项目:
- 使用 Maven 创建
- 使用 Spring Initializr 创建
1、使用 Maven 创建
1、使用 IntelliJ IDEA 创建一个名称为 demo 的 Maven 项目
2、生成项目目录
3、在该 Maven 项目的 pom.xml 中添加以下配置,导入 Spring Boot 相关的依赖。
\demo\pom.xml
<project>
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
...
</project>
4、更新pom文件依赖
5、创建启动类
\demo\src\main\java\com\study\demo\MyApplication.java
package com.study.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author
* @date 2022/11/16 10:21
*/
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
2、使用SpringInitializr创建
1、使用 IntelliJ IDEA 创建一个名称为 demo1 的 Maven 项目
2、选择版本与添加依赖
3、自动生成项目目录
2、启动Spring Boot 项目
1、直接运行启动类 Demo1Application 中的 main() 方法,便可以启动该项目
demo1\src\main\java\com\study\demo\Demo1Application.java
3、添加接口演示
1、新建控制器文件 HelloController
\demo1\src\main\java\com\study\demo\controller\HelloController.java
package com.study.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author QQ:243995716
* @date 2022/11/16 11:23
*/
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
- @Controller:控制器注解
- @ResponseBody:响应为json格式
- @RequestMapping:请求映射配置
2、重启项目 并 访问接口地址
http://localhost:8080/hello
3、测试结果