Sobes.tech
Junior — Middle

Can you explain what Scope Beans are in the context of Spring and what makes them special?

sobes.tech AI

Answer from AI

In Spring, "Scope Beans" refer to the scope of a bean, which determines how long and in what context an instance of the bean exists.

The main scope types in Spring are:

  • Singleton (default): one instance of the bean for the entire Spring container.
  • Prototype: each request for the bean creates a new instance.
  • 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.

The feature of scope is that they allow managing the lifecycle and visibility of objects, which is important for proper state and resource management.

Example of declaring a bean with prototype scope:

@Component
@Scope("prototype")
public class MyPrototypeBean {
    //...
}