Video in progress
What is a bean's default scope, and what other scopes are there?
Instance — singleton (default): one per context; prototype: a new one on every injection or getBean; request: one per HTTP request; session: one per HTTP session; application: one per ServletContext
📖 Answer
| Scope | Instance |
|---|---|
singleton (default) |
one per context |
prototype |
a new one on every injection or getBean |
request |
one per HTTP request |
session |
one per HTTP session |
application |
one per ServletContext |
@Component
@Scope("prototype")
public class CsvExporter { ... }
In practice 95 percent of beans are singletons: services, repositories, controllers. They shouldn't hold state, because many threads use the same instance at the same time.
Watch out: a singleton in Spring means "one per context", not the GoF Singleton pattern. With two contexts you get two instances; and if you new it yourself, that's a new object too.
Sign up to mark studied questions and save your progress.