📖 Java Spring Boot Toàn tập - Giới thiệu Spring Boot và Setup
50 phút

Giới thiệu Spring Boot

Spring Boot là gì?

Spring Boot là framework giúp đơn giản hóa việc phát triển ứng dụng Java với Spring, cung cấp auto-configuration, embedded server và production-ready features.

Ưu điểm

  • Auto-configuration: Giảm thiểu cấu hình
  • Embedded server: Tomcat, Jetty, Undertow
  • Starter dependencies: Quản lý dependencies dễ dàng
  • Production-ready: Actuator, metrics, health checks
  • Hệ sinh thái phong phú: Spring Data, Spring Security, Spring Cloud

Cài đặt môi trường

Yêu cầu

  • JDK 17+ (khuyến nghị JDK 21)
  • Maven hoặc Gradle
  • IDE: IntelliJ IDEA, VS Code

Tạo project với Spring Initializr

# Sử dụng curl
curl https://start.spring.io/starter.zip \
  -d dependencies=web,data-jpa,postgresql,validation,lombok \
  -d type=maven-project \
  -d language=java \
  -d bootVersion=3.2.0 \
  -d groupId=com.example \
  -d artifactId=demo \
  -o demo.zip
unzip demo.zip

Cấu trúc project

demo/
├── pom.xml
├── src/
│   ├── main/
│   │   ├── java/com/example/demo/
│   │   │   ├── DemoApplication.java
│   │   │   ├── controller/
│   │   │   ├── service/
│   │   │   ├── repository/
│   │   │   ├── entity/
│   │   │   └── dto/
│   │   └── resources/
│   │       ├── application.yml
│   │       └── db/migration/
│   └── test/
└── target/

Ứng dụng đầu tiên

Main class

package com.example.demo;

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

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

Controller

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }

    @GetMapping("/hello/{name}")
    public String helloName(@PathVariable String name) {
        return "Hello, " + name + "!";
    }
}

application.yml

spring:
  application:
    name: demo

server:
  port: 8080

logging:
  level:
    com.example.demo: DEBUG

Dependency Injection

Constructor injection (recommended)

@Service
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}

Các loại annotations

  • @Component: Generic component
  • @Service: Business logic
  • @Repository: Data access
  • @Controller / @RestController: Web layer
  • @Configuration: Configuration class

Bài tập thực hành

Hãy tạo ứng dụng Spring Boot đầu tiên với REST endpoints!

📝 Bài tập (1)

  1. Trắc nghiệm về Spring Boot