SpringBoot3.x入门到精通系列:1.3 创建第一个SpringBoot 3.x应用
创建第一个SpringBoot 3.x应用
🎯 学习目标
通过本文,您将学会:
- 使用Spring Initializr创建项目
- 理解SpringBoot项目的基本结构
- 编写第一个REST API
- 运行和测试应用
- 理解SpringBoot的核心注解
🚀 项目创建
1. 使用Spring Initializr创建项目
访问 https://start.spring.io/,配置如下:
Project: Maven Project
Language: Java
Spring Boot: 3.2.0
Project Metadata:Group: com.exampleArtifact: first-appName: first-appDescription: My first SpringBoot 3.x applicationPackage name: com.example.firstappPackaging: JarJava: 17Dependencies:- Spring Web- Spring Boot DevTools- Spring Boot Actuator
2. 项目结构解析
下载并解压项目后,目录结构如下:
first-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/firstapp/
│ │ │ └── FirstAppApplication.java
│ │ └── resources/
│ │ ├── static/
│ │ ├── templates/
│ │ └── application.properties
│ └── test/
│ └── java/
│ └── com/example/firstapp/
│ └── FirstAppApplicationTests.java
├── target/
├── .gitignore
├── mvnw
├── mvnw.cmd
├── pom.xml
└── README.md
3. 核心文件说明
pom.xml - Maven配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- SpringBoot父项目 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.0</version><relativePath/></parent><!-- 项目信息 --><groupId>com.example</groupId><artifactId>first-app</artifactId><version>0.0.1-SNAPSHOT</version><name>first-app</name><description>My first SpringBoot 3.x application</description><!-- Java版本 --><properties><java.version>17</java.version></properties><!-- 依赖管理 --><dependencies><!-- Web Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 开发工具 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><!-- 监控端点 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- 测试依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><!-- 构建插件 --><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
📝 编写第一个应用
1. 主启动类
package com.example.firstapp;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** SpringBoot应用主启动类* @SpringBootApplication 是一个组合注解,包含:* - @SpringBootConfiguration: 标识这是一个配置类* - @EnableAutoConfiguration: 启用自动配置* - @ComponentScan: 启用组件扫描*/
@SpringBootApplication
public class FirstAppApplication {public static void main(String[] args) {// 启动SpringBoot应用SpringApplication.run(FirstAppApplication.class, args);}
}
2. 创建REST Controller
创建 HelloController.java
:
package com.example.firstapp.controller;import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;/*** Hello World控制器* @RestController = @Controller + @ResponseBody* 表示这是一个REST风格的控制器,返回JSON数据*/
@RestController
@RequestMapping("/api")
public class HelloController {/*** 简单的Hello接口*/@GetMapping("/hello")public String hello() {return "Hello, SpringBoot 3.x!";}/*** 带参数的Hello接口*/@GetMapping("/hello/{name}")public String helloWithName(@PathVariable String name) {return String.format("Hello, %s! Welcome to SpringBoot 3.x!", name);}/*** 返回JSON对象的接口*/@GetMapping("/info")public Map<String, Object> getInfo() {Map<String, Object> info = new HashMap<>();info.put("application", "first-app");info.put("version", "1.0.0");info.put("springboot", "3.2.0");info.put("java", System.getProperty("java.version"));info.put("timestamp", LocalDateTime.now());return info;}/*** POST请求示例*/@PostMapping("/greet")public Map<String, String> greet(@RequestBody Map<String, String> request) {String name = request.getOrDefault("name", "World");Map<String, String> response = new HashMap<>();response.put("message", "Hello, " + name + "!");response.put("status", "success");return response;}
}
3. 创建数据模型
创建 User.java
:
package com.example.firstapp.model;/*** 用户数据模型* 使用Java 17的Record特性*/
public record User(Long id,String name,String email,Integer age
) {// Record自动生成构造函数、getter、equals、hashCode、toString方法/*** 自定义方法:检查是否为成年人*/public boolean isAdult() {return age != null && age >= 18;}
}
4. 创建用户控制器
创建 UserController.java
:
package com.example.firstapp.controller;import com.example.firstapp.model.User;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;@RestController
@RequestMapping("/api/users")
public class UserController {// 模拟数据存储private final Map<Long, User> users = new ConcurrentHashMap<>();private final AtomicLong idGenerator = new AtomicLong(1);// 初始化一些测试数据public UserController() {users.put(1L, new User(1L, "张三", "zhangsan@example.com", 25));users.put(2L, new User(2L, "李四", "lisi@example.com", 30));idGenerator.set(3);}/*** 获取所有用户*/@GetMappingpublic List<User> getAllUsers() {return new ArrayList<>(users.values());}/*** 根据ID获取用户*/@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {User user = users.get(id);if (user == null) {throw new RuntimeException("用户不存在: " + id);}return user;}/*** 创建新用户*/@PostMappingpublic User createUser(@RequestBody CreateUserRequest request) {Long id = idGenerator.getAndIncrement();User user = new User(id, request.name(), request.email(), request.age());users.put(id, user);return user;}/*** 删除用户*/@DeleteMapping("/{id}")public Map<String, String> deleteUser(@PathVariable Long id) {if (users.remove(id) == null) {throw new RuntimeException("用户不存在: " + id);}Map<String, String> response = new HashMap<>();response.put("message", "用户删除成功");response.put("id", id.toString());return response;}/*** 创建用户请求模型*/public record CreateUserRequest(String name,String email,Integer age) {}
}
🔧 配置文件
application.properties
# 应用配置
spring.application.name=first-app
server.port=8080# 开发环境配置
spring.devtools.restart.enabled=true
spring.devtools.livereload.enabled=true# Actuator配置
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always# 应用信息
info.app.name=@project.name@
info.app.description=@project.description@
info.app.version=@project.version@
info.app.java.version=@java.version@# 日志配置
logging.level.com.example.firstapp=DEBUG
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
🚀 运行应用
1. 使用Maven运行
# 方式1:使用Maven插件
./mvnw spring-boot:run# 方式2:编译后运行
./mvnw clean package
java -jar target/first-app-0.0.1-SNAPSHOT.jar
2. 使用IDE运行
在IDE中右键点击 FirstAppApplication.java
,选择 “Run” 或 “Debug”。
3. 验证应用启动
看到以下日志表示启动成功:
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v3.2.0)2024-07-24T10:30:00.000+08:00 INFO 12345 --- [first-app] [main] c.e.firstapp.FirstAppApplication : Starting FirstAppApplication using Java 17.0.8
2024-07-24T10:30:01.000+08:00 INFO 12345 --- [first-app] [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path ''
2024-07-24T10:30:01.000+08:00 INFO 12345 --- [first-app] [main] c.e.firstapp.FirstAppApplication : Started FirstAppApplication in 2.345 seconds
🧪 测试应用
1. 使用curl测试
# 测试Hello接口
curl http://localhost:8080/api/hello# 测试带参数的Hello接口
curl http://localhost:8080/api/hello/张三# 测试应用信息接口
curl http://localhost:8080/api/info# 测试用户列表接口
curl http://localhost:8080/api/users# 测试创建用户接口
curl -X POST http://localhost:8080/api/users \-H "Content-Type: application/json" \-d '{"name":"王五","email":"wangwu@example.com","age":28}'# 测试健康检查
curl http://localhost:8080/actuator/health
2. 使用浏览器测试
直接在浏览器中访问:
- http://localhost:8080/api/hello
- http://localhost:8080/api/info
- http://localhost:8080/api/users
- http://localhost:8080/actuator/health
📊 核心注解总结
注解 | 作用 | 示例 |
---|---|---|
@SpringBootApplication | 主启动类注解 | 标注在主类上 |
@RestController | REST控制器 | 返回JSON数据 |
@RequestMapping | 请求映射 | 类级别路径映射 |
@GetMapping | GET请求映射 | 处理GET请求 |
@PostMapping | POST请求映射 | 处理POST请求 |
@PathVariable | 路径变量 | 获取URL中的参数 |
@RequestBody | 请求体 | 接收JSON数据 |
🔗 下一篇
在下一篇文章中,我们将深入了解SpringBoot项目的结构和核心注解的详细用法。
本文关键词: 第一个应用, REST API, Controller, Spring Initializr, Maven