Spring Bean Scopes Introduction

In Spring, bean scope is defined by it’s type, different types of Spring bean instances can be used in different scenarios. There are totally 5 scope types by default.

1. Default Bean Scope Type.

spring-bean-scope-diagram

  1. singleton: This is the default Scope, which means that there will be only one instance in the entire spring container, or in the entire java application.
  2. prototype: Multi-instance type, the container will create a new bean instance for every request to a bean by the client.
  3. request: For spring web application only. When a web action requests an instance of this bean, it will be created by the Spring container, and then saved in the HttpServletRequest object. When the request is complete, the bean will be out of scope and wait for garbage collection.
  4. session: This bean scope type is valid only in web applications also. Defined with this scope, when a web action request this bean, the Spring container will also create an instance of it then save it in the HttpSession object. When the session timeout or invalidate, the bean is invalidated also.
  5. application: This is also for web applications only. This kind of bean will exist in the web application context. One web application will have only one instance.
  6. globalSession: When you use the Portlet container to create a Portlet application, there are a number of portlets in it. Each portlet will save variables in its own session by default. But how to share a global variable object to all the portlets in this Portlet application? Then global-session concept comes out. You can give your spring bean global-session scope, then it can be accessed by all portlets in the application. This scope is not so much different from the session scope in Servlet-based java web applications.

2. How To Specify Bean Scope.

  1. In Spring bean configuration XML file.
     <bean id="helloWorld" class="com.dev2qa.HelloWorld" scope="prototype"/&gt;
  2. Via Java Annotation. When you want to use annotation to define, you should first add the below XML in the bean configuration file. Then Spring will add the corresponding bean definition by scanning annotations.
    <context:component-scan base-package="com.dev2qa"/>
  3. Then you need to use annotations such as @Component on the corresponding java class to indicate that it needs to be added as a bean definition to the corresponding container. @Scope annotation will just be used to point out the scope value.
    @Component
    @Scope("prototype")
    public class HelloWorld {
        
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x