404 Not Found

404 Not Found


nginx

Spring Boot Overview and Setting Up the Environment

Spring Boot makes enterprise-level Java development as easy as building with blocks—with its three key features—automatic configuration, starter dependencies, and an embedded container—it completely eliminates the need for cumbersome XML configuration.

1. What You'll Learn


2. A True Story of a Backend Developer

(1) Pain Point: XML Configuration Hell

Alice is a backend developer who has just taken over a traditional Spring MVC project—the OrderFlow e-commerce order management system. The project contains more than 20 XML configuration files, with data source configurations alone spanning 5 files. Every time she adds a new feature, she has to switch back and forth between three XML files, and it takes new team members an average of two weeks to get up to speed. Deployment also requires installing Tomcat separately and configuring the JNDI data source, and troubleshooting a single environment issue can take half a day.

(2) The Spring Boot Solution

Spring Boot uses the "convention over configuration" philosophy to replace cumbersome XML configuration with zero-configuration startup:

JAVA
@SpringBootApplication
public class OrderFlowApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderFlowApplication.class, args);
    }
}

(3) Revenue

After Alice refactored OrderFlow using Spring Boot: the number of XML configuration files dropped from 20 to 0, the onboarding time for new hires was reduced from 2 weeks to 2 days, deployment requires just a single command—java -jar—and the embedded Tomcat is ready to use right out of the box.


3. Core Features of Spring Boot

(1) Three Core Features

The core concepts of Spring Boot can be summarized with three keywords: auto-configuration, startup dependencies, and embedded container.

100%
graph LR
    A[Spring Boot] --> B[Auto-Configuration<br/>Auto Configuration]
    A --> C[Starter Dependencies<br/>Starter Dependencies]
    A --> D[Embedded Server<br/>Embedded Server]
    B --> B1[Condition-based<br/>Bean Registration]
    C --> C1[Opinionated<br/>Dependency Management]
    D --> D1[Tomcat / Jetty<br/>/ Undertow]
Feature Traditional Spring Spring Boot
Configuration Method Extensive XML / Java Config Auto-configuration + Minimal YAML
Dependency Management Manually specifying versions can lead to conflicts Starting dependencies, with unified version management
Application Server Externally Installed Tomcat Embedded Tomcat, run directly from JAR
Project Structure Requires manual configuration of component scanning @SpringBootApplication One-click enable
Startup Method Deploy WAR to Container java -jar or mvn spring-boot:run

(2) New Requirements for Spring Boot 3.x

Spring Boot 3.x is a major release that requires at least Java 17 and Jakarta EE 9+.

Dimension Spring Boot 2.x Spring Boot 3.x
Minimum Java Version Java 8 Java 17
Namespace javax.* jakarta.*
Spring Framework 5.x 6.x
GraalVM Native Image Experimental Officially Supported
Observability Micrometer Basics In-Depth Integration of Micrometer and OTel
📌 Key Point: The javax → jakarta package name migration in Spring Boot 3.x is the most significant breaking change; all import statements must be updated.


4. A Quick Overview of New Features in Java 17 LTS

(1) The Record Class

Record is an immutable data type that automatically generates a constructor, getters, equals, hashCode, and toString.

(1) ▶ Example: Using Record to Define an Order DTO

JAVA
public record OrderRequest(
    Long productId,
    Integer quantity,
    String customerEmail
) {}

Output:

TEXT
// Execution Successful

(2) Sealed Class

A sealed class restricts which classes can inherit from or implement it, thereby enhancing type safety.

(2) ▶ Example: Defining Payment Status Using a Sealed Class

JAVA
public sealed interface PaymentStatus
    permits Pending, Completed, Failed {}

public record Pending(String transactionId) implements PaymentStatus {}
public record Completed(String transactionId, LocalDateTime paidAt) implements PaymentStatus {}
public record Failed(String transactionId, String reason) implements PaymentStatus {}

Output:

TEXT
// Execution Successful

(3) Text Block

Text Block: Use triple quotes to write multi-line strings and say goodbye to escape characters.

(3) ▶ Example: Writing an SQL Query Using a Text Block

JAVA
String query = """
    SELECT o.id, o.total_amount, c.email
    FROM orders o
    JOIN customers c ON o.customer_id = c.id
    WHERE o.status = 'PENDING'
      AND o.created_at < :cutoffTime
    ORDER BY o.created_at DESC
    """;

Output:

TEXT
// Execution Successful
Feature Java 11 Syntax Java 17 Syntax
Immutable Data Hand-coded Lombok or Boilerplate record Done in One Line
Type Hierarchy Control Unrestricted Inheritance sealed Restricted Subclasses
Multi-line strings Concatenation + \n """ ... """
Switch Expression Statement Expression + Pattern Matching Preview

5. Creating a Project Using Spring Initializr

(1) Introduction to Spring Initializr

Spring Initializr is the official project generator that allows you to quickly create project skeletons via a web interface or IDE integration.

(1) ▶ Example: Using Spring Initializr with curl

BASH
curl https://start.spring.io/starter.zip \
  -d type=maven-project \
  -d language=java \
  -d bootVersion=3.2.5 \
  -d groupId=com.orderflow \
  -d artifactId=orderflow-service \
  -d name=orderflow-service \
  -d packageName=com.orderflow \
  -d javaVersion=17 \
  -d dependencies=web,data-jpa,mysql,validation \
  -o orderflow-service.zip

Output:

TEXT
{"status":"ok","data":{}}

(2) Generated Project Structure

TEXT
orderflow-service/
├── src/
│   ├── main/
│   │   ├── java/com/orderflow/
│   │   │   └── OrderflowServiceApplication.java
│   │   └── resources/
│   │       ├── application.properties
│   │       ├── static/
│   │       └── templates/
│   └── test/
│       └── java/com/orderflow/
│           └── OrderflowServiceApplicationTests.java
├── pom.xml
└── mvnw / mvnw.cmd

(2) ▶ Example: Key dependencies in OrderFlow's pom.xml

XML
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.5</version>
</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-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Output:

TEXT
// Execution Successful

6. Configuring the Development Environment

(1) IDE Selection and Plugins

IDE Recommended Plugins Advantages
IntelliJ IDEA Ultimate Spring Boot Plugin / Spring Initializr Best Spring Support, One-Click Execution
IntelliJ IDEA Community Spring Boot Assistant (third-party) Free but with limited functionality
VS Code Spring Boot Extension Pack Lightweight, ideal for front-end developers transitioning to back-end development

(2) List of Essential Tools

Tool Purpose Installation Verification
JDK 17+ Compile and Run java -version
Maven 3.9+ Build Tool mvn -version
Git Version Control git --version
Postman / curl API Testing Send a Test Request

(1) ▶ Example: Verifying the Development Environment

BASH
# Verify Java version (must be 17+)
java -version
# openjdk version "17.0.9"

# Verify Maven
mvn -version
# Apache Maven 3.9.6

# Verify Git
git --version
# git version 2.43.0

Output:

TEXT
# Command executed successfully

7. OrderFlow: Project Background and Course Roadmap

(1) OrderFlow Business Scenarios

OrderFlow, developed by Alice, is a microservice-based e-commerce order management system. Its core functions include:

Module Function Technical Highlights
Product Management CRUD / Caching / Search JPA + Redis + Caffeine
Order Management Placing Orders / Canceling Orders / Automatic Cancellation Due to Timeout Transactions + Scheduled Tasks + Asynchronous Operations
User Authentication Registration / Login / Role Permissions Spring Security + JWT
Operations and Monitoring Health Checks / Metrics / Trace Actuator + Prometheus + Grafana

(2) Course Roadmap

100%
graph LR
    P1["Phase 1<br/>Getting Started<br/>L01-L06"] --> P2["Phase 2<br/>Core Features<br/>L07-L12"]
    P2 --> P3["Phase 3<br/>Advanced Features<br/>L13-L18"]
    P3 --> P4["Phase 4<br/>Management and Operations<br/>L19-L23"]
    P4 --> P5["Phase 5<br/>Comprehensive Practice<br/>L24-L26"]

8. Comprehensive Example: Creating an OrderFlow Project and Verifying the Environment

JAVA
// OrderflowServiceApplication.java
package com.orderflow;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OrderflowServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderflowServiceApplication.class, args);
    }
}

// controller/HealthController.java
package com.orderflow.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;

@RestController
public class HealthController {

    @GetMapping("/api/health")
    public Map<String, Object> health() {
        return Map.of(
            "status", "UP",
            "service", "OrderFlow",
            "version", "1.0.0"
        );
    }
}
💻 Output:

TEXT
$ curl http://localhost:8080/api/health
{"status":"UP","service":"OrderFlow","version":"1.0.0"}

❓ FAQ

Q What is the relationship between Spring Boot and Spring Framework?
A Spring Framework is the base framework, while Spring Boot is a rapid development scaffolding tool built on top of Spring Framework. It provides auto-configuration, starter dependencies, and an embedded container, allowing you to get started quickly without manual configuration.
Q Is Java 17 required? Can't I use Java 11?
A Spring Boot 3.x requires Java 17 or later; this is the minimum requirement for Jakarta EE 9 or later. If you must use Java 8 or 11, you'll have to use Spring Boot 2.x, but it has reached its end-of-life (EOL) and will no longer receive security updates.
Q Which should I choose, Maven or Gradle?
A Either one works. Maven has a more mature ecosystem and more extensive documentation, so this tutorial uses Maven. Gradle builds faster and is better suited for large, multi-module projects.
Q Can I use a project generated by Spring Initializr right away?
A You can run it right away; it already includes the main startup class and test classes. However, you'll need to add dependencies and code based on your business requirements, such as JPA entities, controllers, services, and so on.
Q Can a record replace all POJOs?
A A record is suitable for immutable data transfer objects (DTOs). If you need a JPA entity (which requires mutability and a no-argument constructor), you should still use a regular class.
Q Is the IDEA Community Edition sufficient?
A The Community Edition lacks the official Spring Boot plugin, but you can still use it for basic purposes with third-party plugins. If your budget allows, the Ultimate Edition offers more comprehensive Spring support and is recommended.

📖 Summary


📝 Exercises

  1. Basic Exercise (Difficulty ⭐): Use Spring Initializr to create a Spring Boot 3.x project that includes the spring-boot-starter-web dependency. After running the project, visit /api/health to return {"status":"UP"}.

  2. Advanced Problem (Difficulty ⭐⭐): Define a Product record in the project that contains the fields id, name, and price, and create a ProductController that returns a hard-coded list of products.

  3. Challenge (Difficulty: ⭐⭐⭐): Use the sealed interface to define OrderStatus (which includes four implementations: PENDING, CONFIRMED, SHIPPED, and CANCELLED), and return different HTTP status codes in the controller based on the different statuses.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏