DEV Community

c_nooknook_daily_prompt
c_nooknook_daily_prompt

Posted on

ติวสอบสัมภาษณ์งาน Java เบื้องต้น ฉบับ มือใหม่ [2]

Spring Framework เบื้องต้น
Java Spring Boot การ build project สามารถทำได้หลายรูปแบบ โดยขึ้นอยู่กับ build tool ที่ใช้ ซึ่งที่นิยมมากที่สุดมี 2 ตัวหลัก ๆ คือ

✅ 1. Gradle
✅ 2. Maven

ทั้งสอง เกี่ยวข้องโดยตรง กับกระบวนการ build, run, test, package, และ deploy ของ Spring Boot project

🔧 Gradle และ Maven คืออะไร?

รายการ Gradle Maven
รูปแบบ config DSL: ใช้ Groovy/ Kotlin DSL XML (pom.xml)
ความยืดหยุ่น สูง (custom script ได้ง่าย) ต่ำกว่า แต่ชัดเจนกว่า
ความเร็วในการ build เร็วกว่า Maven (ใช้ cache) ช้ากว่า Gradle
Learning Curve สูงขึ้นนิดหน่อย เรียนรู้ได้เร็วกว่า

วิธีการ build Project (Build ได้กี่แบบ?)

👉 หากใช้ Gradle:

./gradlew build         # สร้าง JAR
./gradlew bootRun       # รันแอปแบบ development
./gradlew bootJar       # สร้างไฟล์ JAR เฉพาะ Spring Boot
./gradlew clean         # ลบ build เดิมก่อน

Enter fullscreen mode Exit fullscreen mode

👉 หากใช้ Maven:

mvn clean install       # สร้าง JAR และติดตั้งไว้ใน local repo
mvn spring-boot:run     # รันแอป
mvn package             # สร้าง JAR

Enter fullscreen mode Exit fullscreen mode

📦 ผลลัพธ์ของการ Build

  • ได้เป็นไฟล์ .jar หรือ .war (ขึ้นอยู่กับ config)
  • สามารถนำไป deploy ได้ทันที (Spring Boot เป็น self-contained)

🎯 สรุปว่า Gradle/Maven เกี่ยวข้องอย่างไร?

สิ่งที่เกี่ยวข้อง คำอธิบาย
🔗 Build Tool Spring Boot ใช้ Maven/Gradle เพื่อจัดการ dependency, build, run และ deploy
⚙️ Dependency Management Maven: ใช้ pom.xml, Gradle: ใช้ build.gradle เพื่อกำหนดไลบรารี
📄 Script Configuration ใช้ระบุเวอร์ชัน Spring Boot, plugins และ tasks สำหรับ build

✅ สรุปสุดท้าย

  • Spring Boot build ได้หลายแบบ เช่น JAR, WAR, native image (GraalVM)
  • ต้องใช้ build tool เช่น Gradle หรือ Maven ในการจัดการขั้นตอนต่าง ๆ
  • Gradle กับ Maven ทำหน้าที่คล้ายกันแต่มี syntax และประสิทธิภาพที่ต่างกันเล็กน้อย

🌟 GraalVM คืออะไร?
GraalVM คือ High-Performance Virtual Machine ที่สามารถรันหลายภาษาได้ (เช่น Java, JavaScript, Python, Ruby ฯลฯ) โดยมี จุดเด่น คือ:

✅ รองรับการ compile Java application ให้กลายเป็น Native Executable (AOT Compile)
✅ ทำงานเร็วกว่า JVM แบบปกติในบางกรณี
✅ ใช้ memory น้อยลง
✅ Startup time ไวมาก (เช่น 0.01 วินาที เทียบกับ 2-3 วินาทีของ JVM ปกติ)

GraalVM ต่างจาก JVM ปกติยังไง?

ประเด็น JVM ปกติ (OpenJDK) GraalVM (Native Image)
🛠️ Compile Type JIT (Just-In-Time) AOT (Ahead-Of-Time)
⚡ Startup Time ช้า (warm-up ก่อน) เร็วมาก (เกือบทันที)
🧠 Memory Usage ใช้เยอะ ใช้น้อย
🔁 Compatible Libs รองรับทุก lib Java ต้องใช้ lib ที่ support AOT เท่านั้น
🧳 ขนาดไฟล์ Executable ไม่สามารถ run ได้เอง (ต้องใช้ JVM) เป็น binary พร้อม run ได้เลย

🚀 GraalVM กับ Spring Boot
Spring Boot สามารถทำงานร่วมกับ GraalVM ได้ผ่าน Spring Native หรือ Spring Boot 3.x ขึ้นไปที่ใช้ AOT Processing โดยตรง

ตัวอย่าง Build แบบ Native:

./gradlew bootBuildImage --builder paketobuildpacks/builder:tiny

Enter fullscreen mode Exit fullscreen mode

หรือใช้ GraalVM ตรง ๆ:

native-image -jar your-app.jar

Enter fullscreen mode Exit fullscreen mode

ได้ผลลัพธ์เป็นไฟล์ .exe หรือ binary ที่สามารถ run ได้โดยไม่ต้องติดตั้ง Java

📌 ใช้ GraalVM ตอนไหนถึงจะดี?

เหมาะกับ เพราะว่า
💻 Microservices ต้องการ startup เร็ว, ใช้ memory น้อย
🖥️ CLI tools ต้องการ build เป็น binary ขนาดเล็ก
☁️ Serverless ช่วยลด cold-start time
📱 Embedded App มี resource จำกัด

📦 แต่ข้อควรระวัง

  • ไม่รองรับ Reflection บางแบบ (เช่นการใช้ Class.forName()) ต้องกำหนดล่วงหน้า
  • การ build นานมาก (บางครั้งหลักนาที)
  • ต้องเขียนโค้ดให้ AOT-friendly
  • ไม่รองรับทุก third-party lib โดยเฉพาะที่ใช้ dynamic code
คำถาม คำตอบ
GraalVM คืออะไร? VM ที่ compile Java เป็น native binary
ต่างจาก JVM ปกติยังไง? เร็วกว่า, ใช้ memory น้อยกว่า, run ได้ทันที
ใช้กับ Spring Boot ได้ไหม? ได้ โดยใช้ Spring Native หรือ Spring Boot 3.x+
ควรใช้เมื่อไหร่? เมื่อ performance สำคัญ เช่นใน Microservices หรือ Serverless

🔍 AOT คืออะไร?
AOT = Ahead-Of-Time compilation
คือการ compile โค้ดล่วงหน้า (ก่อน runtime) ให้เป็น binary (เครื่องอ่านได้เลย)
ต่างจาก JIT ที่ compile ตอน runtime

📦 ตัวอย่าง:

แบบ ความหมาย
AOT (Ahead-of-Time) Compile เป็น binary ก่อนรัน เช่น GraalVM Native Image
JIT (Just-in-Time) Compile ระหว่างรัน เช่น JVM ปกติ (OpenJDK, HotSpot)

🚀 ทำไม AOT เร็ว?
เพราะมัน ไม่ต้องตีความ หรือ compile ซ้ำ ขณะรันโปรแกรม
จึงได้ผลลัพธ์:

  • ⚡ Startup เร็ว
  • 🧠 ใช้ memory น้อยลง
  • 🐳 เหมาะกับ container, serverless

🧩 AOT-Friendly คืออะไร?

โค้ดของเราต้องเขียนในแบบที่ "สามารถ compile ล่วงหน้า" ได้ โดยไม่ต้องพึ่ง runtime processing หรือ reflection ที่ไม่แน่นอน

❌ ตัวอย่าง "ไม่ AOT-friendly"

Class.forName("com.example.MyClass"); // ใช้ reflection

Enter fullscreen mode Exit fullscreen mode
@Autowired
private Object someBean; // ใช้ dynamic injection แบบที่ compiler เดาไม่ได้

Enter fullscreen mode Exit fullscreen mode

พวกนี้ GraalVM จะไม่สามารถ "คาดเดา" ได้ล่วงหน้า ทำให้ build ไม่ผ่าน หรือรันไม่ได้

✅ ตัวอย่าง "AOT-friendly"

@Autowired
private MyService myService; // แบบเจาะจง class
Enter fullscreen mode Exit fullscreen mode

หรือใช้ annotation ที่ GraalVM รองรับ เช่น @RestController, @ConfigurationProperties แบบ static

📘 ใน Spring Boot 3+

Spring Boot 3.x ใช้ Spring AOT Engine เพื่อ:

  • วิเคราะห์โค้ดทั้งหมด
  • Generate code/metadata ที่ GraalVM เข้าใจได้
  • ลด runtime reflection ลง

✅ สรุป

หัวข้อ ความหมาย
AOT Compile โค้ดล่วงหน้าก่อนรัน
AOT-friendly โค้ดที่เขียนแบบ static ชัดเจน ไม่มี reflection หรือ dynamic code
ทำไมต้องสนใจ เพราะ GraalVM ต้องการ compile ล่วงหน้าให้เร็วและเบา
Spring Boot 3 รองรับ AOT และ Native Image เต็มรูปแบบ

ตัวอย่างการใช้ Spring Boot สร้าง REST Controller ง่าย ๆ

@RestController
public class HelloController {

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

Enter fullscreen mode Exit fullscreen mode

@RestController คือการประกาศว่า Class นี้เป็น Controller แบบ REST

@GetMapping คือการแมป HTTP GET กับ method

Dependency Injection (DI)

@Service
public class UserService {
    // business logic
}

@RestController
public class UserController {
    private final UserService userService;

    // Constructor Injection
    public UserController(UserService userService) {
        this.userService = userService;
    }
}

Enter fullscreen mode Exit fullscreen mode

JDBC (Java Database Connectivity)
JDBC คือ API มาตรฐานของ Java สำหรับเชื่อมต่อและสั่งงานฐานข้อมูลแบบ relational เช่น MySQL, PostgreSQL

ตัวอย่าง JDBC เชื่อมต่อฐานข้อมูล

String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM users");

    while (rs.next()) {
        System.out.println(rs.getString("username"));
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Enter fullscreen mode Exit fullscreen mode

🌐 REST API
REST (Representational State Transfer) คือสถาปัตยกรรมสำหรับสร้าง Web Services ที่ใช้ HTTP Method (GET, POST, PUT, DELETE) ในการจัดการ Resource

HTTP Methods ที่ควรรู้

Method ใช้ทำอะไร?
GET ดึงข้อมูล
POST สร้างข้อมูลใหม่
PUT แก้ไขข้อมูล
DELETE ลบข้อมูล

ตัวอย่าง REST API ด้วย Spring Boot

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

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // return user by id
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        // create user
    }
}

Enter fullscreen mode Exit fullscreen mode

📌 Lombok คืออะไร?
Lombok เป็นไลบรารีของ Java ที่ช่วยลดโค้ดซ้ำซ้อน เช่น getter, setter, constructor, toString() โดยอาศัย annotation-based code generation ที่ compile-time

Lombok Annotations ที่ใช้บ่อย

Annotation ทำหน้าที่
@Getter, @Setter สร้าง getter/setter อัตโนมัติ
@ToString สร้างเมธอด toString()
@EqualsAndHashCode สร้าง equals() และ hashCode()
@NoArgsConstructor สร้าง constructor แบบไม่มี argument
@AllArgsConstructor สร้าง constructor ที่รับทุก field
@RequiredArgsConstructor สร้าง constructor สำหรับ field ที่เป็น final หรือ @NonNull
@Data รวม @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor
@Builder ใช้สร้าง object แบบ builder pattern
@Value ทำให้ class เป็น immutable (เหมือน final + @Data)

ตัวอย่างการใช้ Lombok

import lombok.Data;
import lombok.Builder;

@Data
@Builder
public class User {
    private String name;
    private int age;
}

Enter fullscreen mode Exit fullscreen mode

ผลลัพธ์ที่ได้: class นี้จะมี getter, setter, toString, equals, hashCode และสามารถสร้าง object แบบนี้ได้:

User user = User.builder()
                .name("Alice")
                .age(25)
                .build();

Enter fullscreen mode Exit fullscreen mode

Annotation ใน Java คือชนิดพิเศษของ interface
❌ ไม่ใช่ class (class ธรรมดา)
❌ ไม่ใช่ function

  • Annotation = ป้ายกำกับ (label) ที่อธิบายว่า class หรือ method นี้ "มีความหมายพิเศษ"
  • Annotation คือคำสั่งพิเศษที่ขึ้นต้นด้วย @ ใช้เพื่อ แนบ metadata (ข้อมูลเพิ่มเติม) ให้กับ class, method, field ฯลฯ
  • ไม่ส่งผลต่อ logic โดยตรง แต่สามารถใช้ร่วมกับ framework, tooling, หรือ compile-time processing

  • ใน Java ทุก annotation ถูกสร้างด้วยคีย์เวิร์ด @interface

  • ซึ่งหมายความว่า annotation เป็นชนิดหนึ่งของ interface ที่มี metadata เท่านั้น

  • เบื้องหลัง @interface → Java จะสร้าง interface พิเศษ ที่เก็บเฉพาะ "ค่ากำกับ (metadata)" เท่านั้น ไม่มี logic หรือพฤติกรรมแบบ class ทั่วไป

สรุปเปรียบเทียบ

สิ่งที่เปรียบเทียบ class interface annotation (@interface)
มี logic ได้ไหม ✅ ได้ ❌ ไม่ได้ ❌ ไม่ได้
ใช้ @interface ได้ไหม ❌ ไม่ได้ ❌ ไม่ได้ ✅ ได้
มี method body ได้ไหม ✅ ได้ ❌ ไม่ได้ ❌ ไม่ได้
ใช้สร้าง object ได้ไหม ✅ ได้ ❌ ไม่ได้ ❌ ไม่ได้
ถูก JVM อ่านแบบ metadata ไหม ✅ ใช่
ตัวอย่าง public class MyClass {} interface MyService {} @interface MyAnnotation {}

แล้ว annotation ใช้ยังไง?

@MyAnnotation(value = "dev")
public class Demo {}

Enter fullscreen mode Exit fullscreen mode
  • JVM จะไม่เรียก MyAnnotation แบบ object แต่จะเก็บข้อมูลนี้เป็น metadata
  • เราสามารถใช้ reflection อ่าน metadata เหล่านี้ได้ใน runtime
  • หรือ framework เช่น Spring, JUnit, Hibernate จะใช้ annotation เพื่อกำหนดพฤติกรรม

🧠 สรุปสุดท้ายจำง่าย:

  • ❓ Annotation คือ class ไหม?
  • 🔸 ❌ ไม่ใช่ class
  • 🔹 ✅ เป็น interface แบบพิเศษ (ประกาศด้วย @interface)
  • 🔸 📌 ใช้เพื่อแนบ metadata ไม่ได้มี logic หรือสร้าง instance แบบ class ได้

Spring Boot Annotations ที่ควรรู้
ตัวอย่าง Annotation ที่ใช้บ่อยใน Java

Annotation ใช้ทำอะไร
@Override บอกว่า method นี้ override มาจาก superclass
@Deprecated เตือนว่า method/class นี้เลิกใช้แล้ว
@SuppressWarnings ปิด warning จาก compiler

Annotation ที่ใช้บ่อยใน Spring Framework

Annotation ใช้ทำอะไร
@Component บอกว่า class นี้เป็น bean
@Service ระบุว่าเป็น service layer
@Repository ระบุว่าเป็น repository สำหรับ JPA
@Autowired ให้ Spring inject dependency อัตโนมัติ
@RequestMapping, @GetMapping, @PostMapping ใช้ระบุเส้นทาง HTTP ใน Controller
@RestController รวม @Controller + @ResponseBody
@Configuration, @Bean ใช้กำหนด bean ด้วยมือ

🔽 Annotation ระดับ Class

Annotation คำอธิบาย
@SpringBootApplication รวบรวม @Configuration, @EnableAutoConfiguration, @ComponentScan
@RestController ประกาศว่าเป็น REST API controller
@Service สำหรับ class ที่เป็น business logic
@Repository สำหรับ class ที่ติดต่อ database
@Component ใช้กับ bean ทั่วไป
@Configuration ใช้สร้าง Java config
@EnableAutoConfiguration ให้ Spring ตั้งค่าทุกอย่างให้อัตโนมัติ

🔼 Annotation ระดับ Method / Field

Annotation คำอธิบาย
@Autowired ให้ Spring ฉีด dependency มาให้อัตโนมัติ
@Value อ่านค่าจาก application.properties หรือ yaml
@RequestMapping กำหนด path และ method ของ API
@GetMapping, @PostMapping ตัวย่อของ @RequestMapping(method = …)
@RequestBody, @PathVariable, @RequestParam รับข้อมูลจาก HTTP request
@Bean บอกว่า method นี้ return เป็น Spring bean

🧩 ตัวอย่าง REST API Controller ด้วย Spring + Lombok

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

    private final UserService userService;

    @GetMapping("/{id}")
    public UserDto getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public UserDto createUser(@RequestBody CreateUserRequest request) {
        return userService.createUser(request);
    }
}

Enter fullscreen mode Exit fullscreen mode
@Data
public class CreateUserRequest {
    private String name;
    private int age;
}

Enter fullscreen mode Exit fullscreen mode

📚 สรุปหัวข้อเสริม

  • ✅ Lombok ช่วยลดโค้ดซ้ำซ้อน ทำให้ class สั้น กระชับ (Boilerplate code-โค้ดพื้นฐานที่ต้องเขียนซ้ำ ๆ เพื่อให้ระบบทำงาน แต่ไม่ใช่ logic หลัก)
  • ✅ ใช้ annotation เช่น @data, @builder, @RequiredArgsConstructor บ่อยมากใน Spring
  • ✅ เข้าใจ annotation ของ Spring จะช่วยให้พัฒนาได้รวดเร็ว และอธิบายโค้ดได้เวลาสัมภาษณ์

คำถามสัมภาษณ์เกี่ยวกับ Lombok & Spring Annotations

คำถาม แนวคำตอบ
@Data ต่างจาก @Getter/@Setter อย่างไร? @Data รวมหลาย annotation ในตัวเดียว เช่น toString, equals, hashCode
@Autowired ทำงานอย่างไร? Spring จะ inject bean โดยอัตโนมัติตาม type หรือ name
@Component ต่างจาก @Service หรือ @Repository ไหม? ทั้งหมดเป็น component เหมือนกัน แต่ใช้เพื่อจำแนก role ต่างกัน (best practice)
ใช้ Lombok แล้ว debug ยากไหม? อาจยากขึ้นถ้าไม่เข้าใจว่ามัน generate อะไรบ้าง ต้องดู bytecode หรือใช้ IDE ที่รองรับ

คำถามสัมภาษณ์งานยอดนิยม

คำถาม ประเด็นที่ควรรู้
Java กับ JavaScript เหมือนกันมั้ย? ไม่เหมือนกันเลย
final คืออะไร ใช้กับตัวแปร เมธอด หรือคลาส เพื่อไม่ให้เปลี่ยนแปลง
Overloading vs Overriding Overload: ชื่อเดียว พารามิเตอร์ต่างกัน, Override: เขียนทับจาก superclass
String กับ StringBuilder ต่างกันยังไง? String immutable, StringBuilder mutable และเร็วกว่า
JVM, JRE, JDK ต่างกันยังไง? JVM: รัน, JRE: รัน + ไลบรารี, JDK: ใช้เขียน + compile
Spring Framework คืออะไร? Framework ช่วยพัฒนา Java Web Application โดยเน้น DI และ AOP
JDBC ทำงานอย่างไร? เชื่อมต่อฐานข้อมูลผ่าน API ที่มาตรฐานของ Java
REST API คืออะไร? สถาปัตยกรรมสำหรับการสื่อสารระหว่าง Client-Server ด้วย HTTP

Top comments (0)