IoC Container (Inversion of Control Container)
ตัวจัดการที่คอยสร้างและส่ง dependency ให้ class ต่าง ๆ แทนที่จะให้ class สร้างเอง เป็นหัวใจหลักของ Spring / Spring Boot
เปรียบเทียบ: เหมือนไปร้านอาหาร — แทนที่จะเข้าครัวไปหยิบวัตถุดิบเอง เราแค่สั่งเมนูแล้วพนักงาน (Container) จัดการให้ทุกอย่าง
มันทำงานยังไง (Spring)
1. App เริ่มต้น
2. Spring scan หา class ที่มี @Component, @Service, @Repository
3. สร้าง object ("Bean") เก็บไว้ใน Container
4. Class ไหนมี @Autowired → Container หา Bean ที่ตรงกันมา inject ให้
5. ทุกอย่างพร้อมใช้งาน
ตัวอย่างเต็ม
// 1. สร้าง interface
public interface NotificationService { void send(String msg); }
// 2. Implementation — ติด @Service เพื่อบอก Spring ว่าเก็บไว้ใน Container
@Service
public class LineNotification implements NotificationService {
public void send(String msg) { System.out.println("ส่ง Line: " + msg); }
}
// 3. ใช้งาน — @Autowired แล้ว Spring inject ให้
@Service
public class OrderService {
@Autowired
private NotificationService notification;
public void placeOrder(String item) {
notification.send("สั่งซื้อ " + item + " สำเร็จ");
}
}ถ้ามี Bean หลายตัวที่ implement interface เดียวกัน?
Spring จะ error! วิธีแก้ 3 แบบ:
| วิธี | เมื่อไหร่ควรใช้ | เปรียบเทียบ |
|---|---|---|
@Primary | มีตัวเริ่มต้นชัดเจน | ”ถ้าไม่บอก ให้ใช้ตัวนี้” |
@Qualifier("name") | อยากเลือกเฉพาะตัว | ”เอาตัวนี้แหละ บอกชื่อเลย” |
| ตั้งชื่อ variable ให้ตรง | วิธีง่ายสุด | ”ตั้งชื่อให้ตรง Spring เดาให้” |
IoC Container
| ด้าน | IoC Container (Spring Boot) |
|---|---|
| ใครสร้าง dependency | Container สร้างให้ (อัตโนมัติ) |
| วิธี inject | @Autowired |
| ข้อดี | สะดวก ไม่ต้อง setup เอง |
| ข้อเสีย | มี “magic” — ต้องเข้าใจว่า Spring ทำอะไรให้ |
Related
- Spring / Spring Boot — ใช้ IoC Container เป็นหัวใจ
- Dependency Injection — pattern ที่ IoC Container จัดการให้
- OOP — ต้องเข้าใจ interface และ implementation
- OSIV — เกี่ยวข้องกับการ wrap DataSource ด้วย LazyProxy