bean scope ควบคุมว่า container สร้างอินสแตนซ์กี่ตัวและมันมีอายุยาวแค่ไหน ส่วน lifecycle callback ให้คุณรันโค้ดทันทีหลังจาก bean ถูกสร้าง และก่อนที่มันจะถูกทำลาย
bean scope ควบคุมว่า container สร้างอินสแตนซ์กี่ตัวและมันมีอายุยาวแค่ไหน ส่วน lifecycle callback ให้คุณรันโค้ดทันทีหลังจาก bean ถูกสร้าง และก่อนที่มันจะถูกทำลาย
@Service // singleton by default — one shared OrderService for the whole app
public class OrderService { }
@Component
@Scope("prototype") // fresh instance on every getBean/inject
public class ReportBuilder { }
กับดักคลาสสิก: การ inject prototype เข้าไปใน singleton singleton ถูกเชื่อมโยงเพียง ครั้งเดียว มันจึงเก็บอินสแตนซ์ prototype ตัวเดียวไว้ตลอดไป — คำสัญญา "ใหม่ทุกครั้ง" จึงพังลง แก้ได้ด้วย @Lookup, ObjectProvider<ReportBuilder> หรือ scoped-proxy
@Component
public class ConnectionPool {
@PostConstruct // runs after dependencies are injected, before use
public void open() { /* open sockets, warm caches */ }
@PreDestroy // runs on graceful container shutdown (singletons only)
public void close() { /* release resources */ }
}
สำคัญ: Spring จะ ไม่ เรียก @PreDestroy บน bean แบบ prototype — มันส่งมอบ bean ออกไปแล้วเลิกติดตาม ดังนั้น คุณ เป็นผู้รับผิดชอบการ cleanup เอง
สิ่งนี้แยกคนที่มอง Spring เป็นเวทมนตร์ออกจากคนที่เข้าใจ container บั๊ก singleton-ถือ-prototype เป็นสถานการณ์สัมภาษณ์ยอดนิยม เพราะมันแนบเนียนและก่อบั๊กจริงใน production การรู้ว่า singleton ต้อง ไม่มี state และปลอดภัยต่อ thread (thread-safe) (เพราะถูกใช้ร่วมกันข้ามทุก request thread) คือบทเรียนเชิงปฏิบัติที่ผู้สัมภาษณ์เฝ้าฟัง
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค