Spring Bean Scopes Introduction

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

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, container will create a new bean instance for every request to a bean by client.
  3. request : For spring web application only. When a web action request an instance of this bean, it will be created by Spring container, and then saved in HttpServletRequest object. When the request complete, the bean will be out of scope and wait for garbage collection.
  4. session : This bean scope type is valid only in web application also. Defined with this scope, when a web action request this bean, Spring container will also create an instance of it then save it in HttpSession object. When the session timeout or invalidate, the bean is invalidate also.
  5. application : This is also for web application only. This kind of bean will exist in the web application context. One web application will has only one instance.
  6. globalSession : When you use Portlet container to create Portlet application, there are a number of portlets in it. Each portlet will save variable in their own sesion by default. But how to share a global variable object to all the portlets in this Portlet application? Then global-session concept come out. You can give your spring bean global-session scope, then it can be accessed by all portlet in the application. This scope is not so much different from session scope in Servlet based java web applications.
READ :   Spring Autowire Use @Component, @Repository, @Service and @Controller Annotations
How To Specify Bean Scope
  1. In Spring bean configuration xml file.
     <bean id="helloWorld" class="com.dev2qa.HelloWorld" scope="prototype"/>
  2. Via Java Annotation.
    When you want to use annotation to define, you should first add below xml in bean configuration file. Then Spring will add corresponding bean definition by scanning annotations.

    <context:component-scan base-package="com.dev2qa"/>

    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 {
    	
    }
(Visited 174 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

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