Junior — Middle
Can you explain the purpose and use of the Scope annotation in the context of Spring?
sobes.tech AI
Answer from AI
The @Scope annotation in Spring is used to define the scope of a bean — that is, how long an instance of the bean exists and how it is created.
Main scopes include:
- singleton (default) — one instance of the bean is created for the entire Spring context.
- prototype — a new instance is created each time the bean is requested.
- request — the bean lives within a single HTTP request (for web applications).
- session — the bean lives within an HTTP session.
- application — the bean lives within the ServletContext.
Example usage:
@Component
@Scope("prototype")
public class MyBean {
// each call to getBean(MyBean.class) will create a new object
}
Thus, @Scope allows managing the lifecycle and scope of components in a Spring application.