Junior — Middle
Explain the concept of prototypes in Spring and how they work.
sobes.tech AI
Answer from AI
In Spring, the prototype scope (scope = "prototype") means that each time a bean is requested from the Spring container, a new instance of that bean is created.
This differs from singleton scope (scope = "singleton"), where a single instance is created for the entire application context.
How it works:
- When a bean is declared with the
@Scope("prototype")annotation or in XML configuration, it is marked as prototype. - When the application requests such a bean, Spring creates a new object, initializes it, and returns it.
- The container does not manage the lifecycle of prototype beans after creation; responsibility for their destruction lies with the calling code.
Example:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// fields and methods
}
// Elsewhere
@Autowired
private ApplicationContext context;
public void example() {
MyPrototypeBean bean1 = context.getBean(MyPrototypeBean.class);
MyPrototypeBean bean2 = context.getBean(MyPrototypeBean.class);
// bean1 and bean2 are different instances
}
Used when a new bean instance is needed for each request, for example, to hold state specific to a particular operation.