Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice: Use prototype bean instead of new () operator

I am trying to understand what would be the correct usage of Spring prototype bean. May be the following code sample will help in you understanding my dilemma:

List<ClassA> caList = new ArrayList<ClassA>();
    for (String name : nameList) {
        ClassA ca = new ClassA();

    //or Shall I use protypebean, using method lookup I can inject the dependency of ClassA. 
    // ClassA ca = getPrototypeClassA();

        ca.setName(name);
        caList.add(ca);
    }

So my exact point is in this scenario shall I go with method injection or new() operator. Provide your view with justification.

like image 469
008ak89 Avatar asked Jan 03 '19 05:01

008ak89


People also ask

What is the use of prototype bean?

Prototype: A new instance will be created for a single bean definition every time a request is made for that bean. Request: A new instance will be created for a single bean definition every time an HTTP request is made for that bean. But Only valid in the context of a web-aware Spring ApplicationContext.

Which is better singleton or prototype?

Prototype scope is used for all beans that are stateful, while the singleton scope should be used for stateless beans.

What happens if we have prototype bean in singleton bean?

Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.

What is difference between prototype and request bean scope?

prototype – A new instance will be created every time the bean is requested from the spring container. request – This is same as prototype scope, however it's meant to be used for web applications. A new instance of the bean will be created for each HTTP request.


1 Answers

You can make use of either of the ways, because ultimately client code is responsible for handling the life-cycle of the prototype bean rather than spring container.

According to Spring-docs,

In some respects, you can think of the Spring containers role when talking about a prototype-scoped bean as somewhat of a replacement for the Java 'new' operator. All lifecycle aspects past that point have to be handled by the client.

Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto.

like image 132
Ankur Avatar answered Oct 11 '22 21:10

Ankur