当前位置: 首页 > news >正文

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主启动类注解标注在主类上
@RestControllerREST控制器返回JSON数据
@RequestMapping请求映射类级别路径映射
@GetMappingGET请求映射处理GET请求
@PostMappingPOST请求映射处理POST请求
@PathVariable路径变量获取URL中的参数
@RequestBody请求体接收JSON数据

🔗 下一篇

在下一篇文章中,我们将深入了解SpringBoot项目的结构和核心注解的详细用法。


本文关键词: 第一个应用, REST API, Controller, Spring Initializr, Maven

http://www.dtcms.com/a/310054.html

相关文章:

  • LeetCode 刷题【24. 两两交换链表中的节点、25. K 个一组翻转链表】
  • Ubuntu 开启wifi 5G 热点
  • 数字孪生城市:以虚实映射为起点,开启城市全要素数字化转型新纪元
  • Docker学习其二(容器卷,Docker网络,Compose)
  • FEVER数据集:事实验证任务的大规模基准与评估框架
  • 如何安全管理SSH密钥以防止服务器被入侵
  • Wisdom SSH开启高效管理服务器的大门
  • 企业WEB应用服务器TOMCAT
  • 将Varjo XR技术融入战斗机训练模拟器,有效提升模拟训练沉浸感与效率
  • python简单操作达梦数据库
  • 深入浅出理解WaitForSingleObject:Windows同步编程核心函数详解
  • 蘑兔 AI 音乐:你的专属音乐创作搭子
  • python基础:XPath解析网页数据:xpath简介、xpath语法、xpath节点、节点关系、xpath练习实战
  • 蓝桥杯----DA、AD
  • 3DEXPERIENCE结构树中的类型关系图谱
  • Linux(CentOS 7.9) 卸载、安装MySql 5.7详细步骤教程,包括密码设置、字符集设置等
  • 机器学习②【字典特征提取、文本特征处理(TF-IDF)、数据标准化与归一化、特征降维】
  • 在纯servlet项目中,使用@WebFilter定义了多个filter,如何设置filter的优先级
  • 力扣刷题日常(9-10)(待完善)
  • Python中.format()使用详解和格式化控制台日志场景示例
  • 【C语言入门级教学】字符指针变量
  • 逻辑回归算法中的一些问题
  • React核心:组件化与虚拟DOM揭秘
  • 《React Router深解:复杂路由场景下的性能优化与导航流畅性构建》
  • Rust → WebAssembly 的性能剖析全指南
  • NDI开发指南
  • SQL中的HAVING用法
  • SQL中的LEFT JOIN
  • 图论-最短路Floyd算法
  • OpenAI ChatGPT Agent横空出世:全能工具+实时交互,重新定义AI智能体的终极形态