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

社交网站 cms百度登陆

社交网站 cms,百度登陆,找人做网站都要提供什么,营销型网站价格创建第一个SpringBoot 3.x应用 🎯 学习目标 通过本文,您将学会: 使用Spring Initializr创建项目理解SpringBoot项目的基本结构编写第一个REST API运行和测试应用理解SpringBoot的核心注解 🚀 项目创建 1. 使用Spring Initial…

创建第一个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/413763.html

相关文章:

  • 网站导航是做链接赚钱么建设网络平台的流程
  • 短网址还原网站网站开发市场分析
  • 网站做游客留言做如何开展外贸网络营销
  • 网站开发 工作职责商业网站建设的目的和意义
  • 如何网站客户案例网站怎么做成二维码
  • 自助网站免费做公司网站要素
  • 河南省建设监理协会网站证书查询百度热门排行榜
  • 深圳网站建设类公司为什么用html5做网站
  • 建建建设网站公司电话寻找做网站的
  • 做饲料推广哪个网站好网站搜索引擎优化的步骤
  • 网站建设方案就玄苏州久远网络网络营销案例分析心得
  • seo网站推广报价刷单网站搭建
  • 网站开发要学的代码做物流的网站都有什么作用
  • 做平台是做网站和微信小程序的好别php网站如何编辑
  • 域名还在备案可以做网站吗上传网站怎么安装
  • 彩票网站怎么做ip管理建设全网营销型网站
  • 网站开发团队成员腾讯开放平台
  • 状元村建设官方网站wordpress 音乐
  • 外贸建站注意事项怎么找客户渠道
  • 多城市网站建设怎么做宣传网页
  • 怎么做百度网站验证厦门的商城网站建设
  • 江苏城乡建设局网站编写app用什么软件
  • 黑龙江省营商环境建设监察局网站贺州网站推广
  • wordpress主题论坛静态网站怎么优化
  • 纳溪区城乡住房建设局网站search搜索引擎
  • 宁波网站制作费用网页制作与设计项目策划书
  • 钱宝网站怎么做任务软文推广营销服务平台
  • 广西贵港建设集团有限公司网站自己想做网站
  • 怎样建外贸网站网站开发 沈阳
  • 网站建设可上传视频的wordpress编辑主体