Thursday, 14 September 2017

What are different bean scopes and Bean creation procedures ?


Default behavior of Bean creation
Objects are created by Spring container using the Factory pattern.
An object can reference other objects from Spring container by using bean ID.
Upon initialization of ApplicationContext, it reads Spring XML, looks for the beans and initialize all spring beans.
On calling of getBean method, it just provides the initialized bean objects.


We can configure :
- A bean to initialize itself only when a getBean is called.
- ApplicationContext to initialize beans when a getBean is called.




BASIC BEAN SCOPES (2)
1. Singleton

Only one per Spring container. (Default)
Initialized always when ApplicationContext is initialized and doesn't wait for getBean call.
Every getBean call or ref configuration provides same single object.

2. Prototype
New bean created with every request.
Every getBean call or ref configuration provides a new object.

   

WEB AWARE SCOPES (3)
Spring understands well the scopes (request/session/) used with Servlet API.
1. Request

For every HTTP request, a new bean object will be created.
There would be same object used in single request scope.
 

2. Session
Bean object created per HTTP session.
No matter how many requests are coming in a session, a single object will be used throughout the single session.

3. Global session

One bean object per global session of Portlet.
Only applicable for Portlet context.

 

DEFINING SCOPE FOR BEAN
<bean id="employee" class="com.genius.example.Employee" 

      scope="prototype">
  ...
</bean>




NOTE ON SINGLETON
Singleton is per Spring container. So it is not pure Singleton.
It is possible to have multiple Spring container running in a JVM.
So, it is possible to have 2 different bean objects (singleton) in 2 different Spring containers, even they are running in same JVM.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.