Nicky
Nicky

Reputation: 1065

Actual business scenrio where we use Prototype scope in spring?

I was readign about differnt scopes for beans in Spring.

Everytime I have created bean in xml , I have never use scope property, which means It was SingleTon."

For prototype I read that " Prototype scope is preferred for the stateful beans"

What is meant by stateful beans? Can someone give me realtime example, where we have prototype scope?

Upvotes: 0

Views: 247

Answers (1)

cehdmoy
cehdmoy

Reputation: 44

Since singleton is one instance for the whole application, and this object (I'm speaking about the patter, not even spring yet) if had some state for the example name. This field called name should be fine while just one thread calls the object. BUT singleton is one object for application as I said before.

A typical example in spring

@Component
MyComponent{

 private String name;

 public void editName(String newName)
  {
    name=newName
  }

}

ASAP more than one thread call this bean, you will have race conditions (you should read about it ). That's why a singleton must not have state but could have other dependencies (dependency injection).

If you use prototype scope, spring will create one object per use, so in the example name will not be shared and there is any race condition, that's fine!!

Upvotes: 1

Related Questions