Spring Boot for Beginners (2026 Edition)

Build a Spring Boot 3 application from zero: starter dependencies, auto-configuration, application.yml, RESTful APIs, validation, unit testing and jar packaging with full source code.

BeginnerUpdated 2026-10-30142K views

Why Spring Boot

Spring Boot is the de facto Java backend framework. It auto-configures the Spring container, embeds Tomcat so a jar runs as a web server, provides starter dependency bundles, and includes production features like metrics and health checks (actuator).

# 用 Spring Initializr 生成项目(或通过 IDEA 向导)
curl https://start.spring.io/starter.zip \
  -d type=maven-project -d language=java \
  -d bootVersion=3.5.0 -d baseDir=demo \
  -d dependencies=web,validation,lombok \
  -o demo.zip

# 运行
./mvnw spring-boot:run
java -jar target/demo-0.0.1-SNAPSHOT.jar

Project Structure and pom.xml

demo/
├── pom.xml
└── src/main/
    ├── java/com/example/demo/
    │   ├── DemoApplication.java      // 启动类
    │   ├── controller/
    │   ├── service/
    │   ├── repository/
    │   └── entity/
    └── resources/
        └── application.yml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
</dependencies>
Starters pull in a tested set of transitive dependencies. spring-boot-starter-web brings embedded Tomcat + Spring MVC + Jackson JSON.

Auto-Configuration Principles

@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan. Spring Boot scans the classpath and, when a class is present (e.g., Tomcat, Jackson), creates beans that match — @ConditionalOnClass / @ConditionalOnMissingBean annotations decide whether each auto-configuration applies. You can always override any bean by defining your own.

Writing a RESTful API

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    // 构造注入(推荐,final + 构造器)
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public User getById(@PathVariable Long id) {
        return userService.getById(id);
    }

    @PostMapping
    public User create(@Valid @RequestBody UserDto dto) {
        return userService.create(dto);
    }

    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody UserDto dto) {
        return userService.update(id, dto);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        userService.delete(id);
    }
}

// DTO 与校验
public record UserDto(
    @NotBlank String name,
    @Email String email,
    @Min(0) Integer age) {}

Return objects directly — Spring serializes them to JSON via Jackson. Add @Valid to trigger Bean Validation. A unified exception handler with @RestControllerAdvice converts validation exceptions into clean error responses.

Configuration Files

# application.yml
server:
  port: 8080

spring:
  application:
    name: demo
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
    username: root
    password: ${DB_PASSWORD:root}    # 环境变量覆盖
  jpa:
    hibernate:
      ddl-auto: update

logging:
  level:
    com.example.demo: DEBUG
  • Load order: application.yml -> application-{profile}.yml, activate profiles with spring.profiles.active.
  • Externalize configs at runtime with command line args or env vars: java -jar app.jar --server.port=9000.

Unit Testing and Packaging

@SpringBootTest
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;      // 模拟 HTTP 调用

    @Test
    void shouldGetUser() throws Exception {
        mockMvc.perform(get("/api/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.name").value("Alice"));
    }
}
./mvnw clean package      # 生成可执行 jar
target/demo-0.0.1-SNAPSHOT.jar
nohup java -Xms512m -Xmx512m -jar demo.jar > app.log 2>&1 &
# 生产建议加 -XX:+UseG1GC / -XX:MaxRAMPercentage=75

The fat jar embeds Tomcat — no external server needed. For Docker, copy the jar into an eclipse-temurin:21-jre image and set the entrypoint.

Friends & Partners