Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
Anupam Gupta Avatar asked May 27 '11 18:05

Anupam Gupta


People also ask

How we can create custom scope in Spring?

Let's begin to define our custom scope class: public class TenantScope implements Scope { private Map<String, Object> scopedObjects = Collections. synchronizedMap(new HashMap<String, Object>()); private Map<String, Runnable> destructionCallbacks = Collections. synchronizedMap(new HashMap<String, Runnable>()); ... }

Why do we need prototype scope in Spring?

Prototype Scope:If the scope is declared prototype, then spring IOC container will create a new instance of that bean every time a request is made for that specific bean. A request can be made to the bean instance either programmatically using getBean() method or by XML for Dependency Injection of secondary type.

Can we create custom scope in Spring boot?

As of Spring 2.0, we can define custom spring bean scope as well as modify existing spring bean scopes (except singleton and prototype scopes).

Is it possible to create a custom scope?

Scopes are just annotations and you can create your own ones where needed.


1 Answers

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.

like image 182
Bozho Avatar answered Sep 22 '22 02:09

Bozho