Scope xác định vòng đời + số instance của bean.
| Scope | Instance | Dùng khi |
|---|---|---|
| singleton (default) | 1 dùng chung toàn app | Stateless service, repository |
| prototype | Mỗi lần inject/getBean tạo mới | Stateful object (command, builder) |
| request / session | 1 / HTTP request / session (Web) | Request / session state |
Khai báo scope khác default: @Scope("prototype") trên class bean.
Bẫy lớn nhất: inject prototype vào singleton → Spring inject 1 lần lúc startup → singleton giữ cùng 1 prototype instance mãi mãi. Fix: lấy instance mới qua ApplicationContext.getBean() hoặc method @Lookup.
Singleton phù hợp 99% Spring bean vì stateless.