Câu hỏi phỏng vấn Spring
Câu hỏi

How does the scope Prototype work?

Câu trả lời

The scope Prototype in Spring Framework is used to define beans that should have a non-singleton lifecycle. When a bean is set to prototype scope, the Spring IoC (Inversion of Control) container creates a new instance of the bean each time it is requested or injected into another bean. This is in contrast to the singleton scope, which is the default in Spring, where only one instance of the bean is created and shared across the entire container.

Here's how the prototype scope works:

  1. Bean Definition: A bean is defined with the scope set to prototype. This can be done either in the XML configuration by setting the scope attribute to prototype or in Java configuration using the @Scope annotation with the value ConfigurableBeanFactory.SCOPE_PROTOTYPE.

  2. New Instance Creation: Every time a request is made for a prototype bean, the Spring container creates a new bean instance. This is true whether the request is made programmatically using the getBean() method or through dependency injection.

  3. Post-initialization: After the new bean instance is created, Spring will perform any necessary dependency injection and invoke any defined post-initialization lifecycle methods or callbacks.

  4. No Pre-destruction Callback: Unlike singleton beans, the Spring container does not manage the complete lifecycle of a prototype bean. Specifically, it does not call pre-destruction lifecycle callbacks or methods. Once the prototype bean is handed over to the client, the container does not keep track of it or manage its complete lifecycle[1][5][6].

  5. Client Responsibility: It is the responsibility of the client code to manage the lifecycle of the prototype bean beyond its initial creation and dependency injection. This includes the responsibility to clea...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What are ORM's Spring supports?

junior

How to integrate Java Server Faces (JSF) with Spring?

senior

What are some benefits of using Spring Transactions?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào