Spring Boot 3 Introductory Guide: From Zero to Self-Contained RESTful API Development
Spring Boot 3 Core Cognition
Spring Boot 3 Core Ecosystem Panorama
- Core Dependencies: spring-boot-starter-web (Web Development) & spring-boot-starter-test (Testing)
- Data Layer: MyBatis/MyBatis-Plus, Spring Data JPA, Redis Starter
- Security Layer: spring-boot-starter-security (Authentication and Authorization)
- Tooling: Lombok, Knife4j (API Documentation), Spring Boot DevTools (Hot Deployment)
Why Choose Spring Boot? — Saying Goodbye to Verbose Configuration in Java Backend Frameworks
- Key Pain Points Addressed by Spring Boot: Bloated XML Configuration in Traditional Spring Projects, Dependency Version Conflicts, and Complex Deployment
- Spring Boot Core Features: Auto-configuration, Starters, and Embedded Tomcat/Jetty
- Practical Scenario Comparison: Code Volume Difference Between Traditional Spring MVC and Spring Boot Development for the Same Interface
- Spring Boot Use Cases: Small to Medium-Sized Projects, Microservices Architecture, and Rapid Prototyping Development
Spring Boot 2 vs 3 Key Differences (Pitfall Avoidance)
- Version Requirement: Spring Boot 3 Requires Java 17+ (with JDK 17 Installation Verification Steps)
- API Package Migration: javax.* → jakarta.* (e.g., jakarta.servlet.http.HttpServletRequest)
- Automated Configuration Optimization: Adjustments to Default Starter Configurations (e.g., Default Logging Framework, Data Source)
- Ecological Adaptation: Compatibility Notes for Third-Party Components (MyBatis, Redis)
Spring Boot and the Spring Ecosystem
- Spring Boot ≠ Replacement for Spring: It's 'Simplified Encapsulation' of the Spring Framework
- Spring Boot + Spring MVC: The Core Combination for Web API Development
- Spring Boot + Spring Data: A Popular Combination for Simplifying Database Operations
- Selection Recommendations: Use Spring Boot for Small Projects, Combine with Spring Cloud for Large-Scale Projects
Development Environment Setup and Project Initialization
Basic Environment Configuration: JDK 17+ Installation and Verification
- Windows System: JDK 17 Download (Oracle/OpenJDK), Environment Variable Configuration (JAVA_HOME/Path)
- Linux/Mac Systems: Installing OpenJDK 17 via brew/apt and Verifying with java -version in Terminal
- FAQ: JDK Version Conflicts (Uninstalling Old Versions) and Environment Variable Configuration Issues
- Recommended Tool: SDKMAN (One-Click JDK Version Switching)
Quickly Create Projects with Spring Initializr (Illustrated Tutorial)
- Online Address: https://start.spring.io/ - Interface Explanation (Project/Language/Version Selection)
- Key Steps: Choosing Spring Boot 3.x, Adding Starter Dependencies (Web, Lombok, MySQL Driver)
- Project Metadata: Group/Artifact/Name/Description Specification (e.g., com.example.demo)
- Download Project: Create a ZIP Archive and Extract, IDEA Import Maven Project (Automatic Dependency Loading)
Spring Boot 3 Project Directory Deep Analysis
- Core Directory: src/main/java (source code), src/main/resources (configuration/static resources), src/test (tests)
- Key Files: DemoApplication.java (Startup Class), application.properties/yml (Configuration File)
- Parsing pom.xml: Parent Dependencies (Unified Version), Dependencies (Starter Dependencies), and Build (Packaging Configuration)
- .gitignore: Files to Ignore (target, .idea, *.iml)
IDEA Development Tool Optimization (Efficiency Doubled)
- Essential Plugins: Spring Boot Helper (Configuration Hint), Lombok (Annotation Support), MyBatisX (Code Generation)
- Configuration Options: Auto Import Package, Build Version (Set to 17), Maven Mirror (Aliyun Origin Acceleration)
- Keyboard Shortcuts: Run Project (Shift+F10), Format Code (Ctrl+Alt+L)
- Debugging Configuration: Launching Projects in IDEA and Viewing Console Logs
First Demo: Hello World Interface Development and Debugging
- Coding: Create a controller package in the same directory as DemoApplication and add HelloController.java
- Core Annotation: @RestController and @GetMapping("/hello") Explained
- Starting the Project: Click the main method of DemoApplication to view "Started DemoApplication in x seconds" in the console.
- API Debugging: Using Postman to Access http://localhost:8080/hello and View the Response
- Frequently Asked Questions: Port Conflicts (Modify server.port in application.yml), Startup Errors (Missing Dependencies)
Spring Boot 3 Fundamentals and Core Capabilities
Controller Development: Core Annotations for Defining RESTful Interfaces
- @RestController: Equivalent to @Controller + @ResponseBody (returns JSON instead of HTML pages)
- Request Method Annotations: @GetMapping/@PostMapping/@PutMapping/@DeleteMapping Correspond to HTTP Methods
- Interface Path Conventions: RESTful Style (e.g., /users/{id} instead of /getUserById)
- Example: Writing a GET interface that returns a list of users and creating user POST interfaces
Parameter Handling: Parsing Various Parameters Passed from the Front-End
- Path Variable: Retrieving URL Path Parameters (e.g., 'id' from /users/{id})
- Retrieving URL Query Parameters (e.g., /users?name=Zhang San)
- @RequestBody: Getting JSON data from POST/PUT request body (with entity class receiving example)
- Getting Request Headers and Parameters (e.g., Tokens)
- Parameter Validation: @NotBlank/@NotNull Basic Validation (Combined with Entity Class)
Basic Data Operation Syntax
- Adding Dependencies: Introducing mybatis-plus-boot-starter (Compatible with Spring Boot 3)
- Configuring the Database: Configuring MySQL Address, Username, Password, and Driver Class in application.yml
- Creating an Entity Class: User.java (@Data/@TableName Annotations)
- Creating a Mapper Interface: UserMapper.java Inheriting from BaseMapper
- Testing: Injecting UserMapper in the Controller and Calling selectList/insert/deleteById Methods
Response Packaging: Unified Interface Response Format (Mandatory Specification)
- Why Standardization is Important: Avoiding Inconsistent Return Formats (Some Returns as Objects, Some as Strings)
- Defining the Result Class: Including Code, Message, and Data
- Status Code Standards: 200 Success, 400 Bad Request, 500 Internal Server Error
- Case Study: Refactoring HelloController to Return Result.success("Hello World")
Basic Configuration: Core Configuration Items in application.yml
- Server Configuration: server.port (Port), server.servlet.context-path (Context Path)
- Database Configuration: spring.datasource.url/username/password/driver-class-name
- Log Configuration: logging.level.root=INFO, logging.level.com.example=DEBUG
- Configuration File Formats: YAML vs. Properties (YAML is more concise and recommended)
Entry-Level Practice: User Management Interface Development
Practical Preparation: Database Table Design and Environment Setup
- Creating the user table: id (primary key), username (username), password (password), create_time (creation time)
- SQL Statement: CREATE TABLE user (id BIGINT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(100) NOT NULL, create_time DATETIME DEFAULT CURRENT_TIMESTAMP)
- Configuring MyBatis-Plus: Enable Logging (View Generated SQL), Set Primary Key Auto Increment
Complete Development: User CRUD Interface Implementation
- Query All Users: @GetMapping("/users") calls userMapper.selectList(null)
- New User: @PostMapping("/users") receives a @RequestBody User object and calls insert
- Querying a Single User: Calling selectById via @GetMapping("/users/{id}")
- Update User: Calling updateById via @PutMapping("/users/{id}")
- Deleting User: @DeleteMapping("/users/{id}") - deleteById
- Wrap Each API Endpoint with a Result Return, Handling Null Values and Parameter Errors
API Documentation: Integrating Swagger3 (SpringDoc)
- Adding Dependencies: springdoc-openapi-starter-webmvc-ui
- Configuration Options: springdoc.api-docs.path=/api-docs, springdoc.swagger-ui.path=/swagger-ui.html
- Annotation Enhancement: @Tag (Interface Class Description), @Operation (Interface Method Description), @Parameter (Parameter Description)
- Access Test: http://localhost:8080/swagger-ui.html Online Debugging Interface
Project Packaging and Docker Deployment
- Maven Packaging: Execute mvn clean package -DskipTests to generate target/*.jar files
- Running a JAR Locally: java -jar demo-0.0.1-SNAPSHOT.jar
- Writing a Dockerfile: Using openjdk:17-slim, Copying JARs, Exposing Ports
- Building an Image: docker build -t springboot-demo:v1 .
- Starting a Container: docker run -d -p 8080:8080 --name demo springboot-demo:v1
Troubleshooting Manual for Common Issues
- Database Connection Failed: Check URL, Username, Password, and Ensure MySQL Service is Running
- Interface 404: Check @RequestMapping Path and Controller Annotation (@RestController)
- Parameter Parsing Exception: Check if @RequestBody entity class fields match the JSON and if there are type errors.
- Dependency Conflicts: Check for Duplicate Dependencies in pom.xml and Use mvn dependency:tree to Analyze
- Launch Failed: Check the Console Logs for Errors Starting with "Caused by"