5

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?

Nick Bastin
  • 30,415
  • 7
  • 59
  • 78
Anupam Gupta
  • 1,591
  • 8
  • 36
  • 60

2 Answers2

4

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • thanks @Bozho for explaining the problem with apt example but I am a newbie in Java EE and have only spring reference manual as my source of spring information. can you plz suggest some good link/reference-documentation/book for detailed example of these scopes. – Anupam Gupta May 30 '11 at 06:50
  • and as per the answer given by Yohan my understanding is "we use custom scope for performance concern (in application-context)" and regarding web-context - for maintaining session specific details (scope per session), for handling information related to single request (scope per request) and flash and conversation are created as mentioned by you in your answer – Anupam Gupta May 30 '11 at 06:56
  • the spring documentation should be sufficient. – Bozho May 30 '11 at 07:11
3

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).

Yohan Liyanage
  • 6,840
  • 3
  • 46
  • 63