Anupam Gupta
Anupam Gupta

Reputation: 1687

Why would we use custom scope in spring? When is it needed?

Can any one please help me in understanding custom scope. I went through manual and through many online example and understood how it is being implemented. But, I am still not clear why we need a custom proxy, and why we will go for, limiting the scope of the bean.

As i know that for a singleton- we use singleton when we want a single bean to be given to all references & we use prototype when we want a new reference to be given each time the bean is referenced.

Now my understanding regarding Custom scope is
Custom Scope- we use custom scope as a mid-way between the two that is neither we want to pass single reference nor a new reference every time.. but then it is more close to singleton where we are passing the same bean every time, just from our preferred location(such as underlying threadlocal or map).

please do help me making my concept clear ..The main question here is Why custom scope ? and When is it required?

Upvotes: 5

Views: 1523

Answers (2)

Yohan Liyanage
Yohan Liyanage

Reputation: 7000

That actually depends on the problem at hand. For instance, you might want to create a pre-defined number of instances of a particular bean, but not more than that. So until this number is met, you keep creating new instances, but once the number is met, you return existing instances in a balanced manner.

This could be applied to a problem where the instance takes up significant amount of resources (ex. memory) but speeds up the application if a new instance is used. So you could create a feasible amount of new objects when needed, and delegate into existing ones when the number of instances go beyond the that amount(compromising performance over resource utilization).

Upvotes: 3

Bozho
Bozho

Reputation: 597106

In different context. For example - in a web application. Two scopes are defined there - "request" and "session". However, these are sometimes not sufficient. Often there is a need for a "flash" scope (lasts for one request and the subsequent redirect) or "conversation" scope (lasts for a sequence of requests forming a conversation).

In such, and similar cases, a custom scope is used.

Upvotes: 5

Related Questions