0

[Java Backend Zero to Hello] BÀI 5.2: SPRING BOOT CƠ BẢN

Java Backend Zero to Hello

📚 Bài viết thuộc series Java Backend Zero to Hello 📌 Phần: Phase 5: Spring Framework & Spring Boot | Bài 48/86


BÀI 5.2: SPRING BOOT CƠ BẢN

Mục tiêu

  • Hiểu Spring Boot và lợi ích
  • Tạo project Spring Boot
  • Cấu hình application.properties/yml
  • Sử dụng Spring Boot Starter

1. SPRING BOOT LÀ GÌ?

Spring Boot là framework giúp tạo ứng dụng Spring độc lập, sẵn sàng chạy với cấu hình tối thiểu.

Lợi ích

  • Auto-configuration - Tự động cấu hình
  • Embedded server - Tomcat, Jetty nhúng sẵn
  • Starter dependencies - Gói dependency tiện lợi
  • Production-ready - Actuator, health check
  • No XML config - Cấu hình bằng annotation

So sánh Spring vs Spring Boot

Spring Spring Boot
Cần nhiều config Auto-config
Cần external server Embedded server
WAR file JAR file
Phức tạp cho người mới Dễ bắt đầu

2. TẠO PROJECT

2.1 Spring Initializr

  • Truy cập: https://start.spring.io/
  • Chọn: Project (Maven), Language (Java), Spring Boot version
  • Thêm dependencies
  • Download và mở trong IDE

2.2 Từ IntelliJ

  • File → New → Project → Spring Initializr

2.3 Cấu trúc project

my-app/
├── pom.xml
├── src/
│   ├── main/
│   │   ├── java/com/example/
│   │   │   └── Application.java
│   │   └── resources/
│   │       ├── application.properties
│   │       ├── static/        # HTML, CSS, JS
│   │       └── templates/     # Thymeleaf
│   └── test/
│       └── java/com/example/
│           └── ApplicationTests.java
└── target/

3. @SPRINGBOOTAPPLICATION

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

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan


4. STARTER DEPENDENCIES

Starter Mô tả
spring-boot-starter-web Web, REST, Tomcat
spring-boot-starter-data-jpa JPA, Hibernate
spring-boot-starter-security Spring Security
spring-boot-starter-test JUnit, Mockito
spring-boot-starter-validation Bean Validation
spring-boot-starter-actuator Monitoring
spring-boot-starter-thymeleaf Template engine
spring-boot-starter-mail Email
spring-boot-starter-cache Caching
spring-boot-starter-data-redis Redis

Thêm vào pom.xml

<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>

5. APPLICATION.PROPERTIES / YML

5.1 application.properties

# Server
server.port=8080
server.servlet.context-path=/api

# Database
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

# Logging
logging.level.com.example=DEBUG
logging.level.org.springframework=INFO

# Custom
app.name=MyApp
app.version=1.0.0

5.2 application.yml (khuyến nghị)

server:
  port: 8080
  servlet:
    context-path: /api

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: password
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect

logging:
  level:
    com.example: DEBUG
    org.springframework: INFO

app:
  name: MyApp
  version: 1.0.0

6. ĐỌC CONFIG VỚI @VALUE VÀ @CONFIGURATIONPROPERTIES

6.1 @Value

@Component
public class AppConfig {
    @Value("${app.name}")
    private String appName;

    @Value("${app.version:1.0.0}")  // Default value
    private String version;
}

6.2 @ConfigurationProperties (khuyến nghị)

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private String name;
    private String version;
    private Database database = new Database();

    // getters, setters

    public static class Database {
        private String url;
        private int poolSize;
        // getters, setters
    }
}
app:
  name: MyApp
  version: 1.0.0
  database:
    url: jdbc:mysql://localhost:3306/mydb
    pool-size: 10

Enable: @ConfigurationPropertiesScan trên main class.


7. PROFILES

7.1 File cấu hình

application.yml          # Mặc định
application-dev.yml       # Dev
application-prod.yml      # Production

7.2 application-dev.yml

spring:
  datasource:
    url: jdbc:h2:mem:testdb
logging:
  level:
    com.example: DEBUG

7.3 application-prod.yml

spring:
  datasource:
    url: jdbc:mysql://prod-server:3306/mydb
logging:
  level:
    com.example: INFO

7.4 Kích hoạt

java -jar app.jar --spring.profiles.active=prod

Hoặc trong application.yml:

spring:
  profiles:
    active: dev

8. CHẠY ỨNG DỤNG

8.1 Từ IDE

  • Run Application.java

8.2 Từ Maven

mvn spring-boot:run

8.3 Tạo JAR

mvn clean package
java -jar target/my-app-1.0.0.jar

8.4 Với Docker

FROM eclipse-temurin:17-jre
COPY target/my-app-1.0.0.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]

9. COMMAND LINE RUNNER

Chạy code khi ứng dụng khởi động.

@Component
public class StartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("App started!");
        // Khởi tạo data, cache, etc.
    }
}

10. BÀI TẬP THỰC HÀNH

Bài 1: Tạo project Spring Boot

  1. Tạo project với Spring Initializr
  2. Thêm dependencies: web, data-jpa, mysql
  3. Tạo REST API đơn giản

Bài 2: Cấu hình đa profile

Tạo 2 profile dev và prod với database khác nhau.

Bài 3: ConfigurationProperties

Tạo class config đọc các thuộc tính tùy chỉnh.


11. TÓM TẮT

Khái niệm Mô tả
Spring Boot Framework auto-config
@SpringBootApplication Main annotation
Starter Gói dependency
application.yml File cấu hình
@ConfigurationProperties Bind config vào class
Profile Cấu hình theo môi trường
spring-boot:run Chạy từ Maven

Bài tiếp theo: 5.3 Bean & Dependency Injection


🧭 Điều Hướng Series

⬅️ Bài trước: BÀI 5.1: TỔNG QUAN SPRING FRAMEWORK

📋 Lộ trình tổng quan: Xem Toàn Bộ Series

➡️ Bài tiếp theo: BÀI 5.3: BEAN & DEPENDENCY INJECTION


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí