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.
- 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.
- prototype: Multi-instance type, the container will create a new bean instance for every request to a bean by the client.
- 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.
- 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.
- 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.
- 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.
- In Spring bean configuration XML file.
<bean id="helloWorld" class="com.dev2qa.HelloWorld" scope="prototype"/>
- 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"/>
- 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 { }