Skip to main content

What is Bean scope in Spring MVC framework with Example

What is Bean scope in Spring MVC framework with Example

Bean scope in Spring framework or Spring MVC are scope for a bean managed by Spring IOC container. As we know that Spring is a framework which is based on Dependency Injection and Inversion of Control and provides bean management facilities to Java application. In Spring managed environment bean (Java Classes) are created and wired by Spring framework. Spring allows you to define how those beans will be created and scope of bean is one of those details. This Spring tutorial is next on my earlier post on Spring like how to implement LDAP authentication using Spring security and  How to limit number of user session in web application, if you haven’t read them already you may find them useful. 

In spring framework bean declared in ApplicationContext.xml can reside in five scopes:

1) Singleton (default scope)
2) prototype
3) request
4) session
5) global-session

Singleton and prototype are two common bean scope which is available on all Spring Application Context while requestsession and global session bean scope are only available on Web aware application Context like WebApplicationContext.


bean scope in Spring 2.5 and spring 3.0Singleton bean scope is default scope for bean declared in Spring and applicable when you don't specify scope attribute while specifying bean details in ApplicationContext.xml or Spring configuration file. Singleton bean scope is like Singleton pattern in Java where only one instance of bean is created per Spring container. So no matter how many times you call getBean() method, same bean instancewill be returned if its bean scope is declared as Singleton. While in case of prototype bean scope, every getBean() call creates a new instance of Spring bean. Difference between Singleton and prototype bean scope is also a popular Spring question.

On the other hand request bean scope allows each HTTP request to have its own instance of bean created and supplied by Spring framework, while Session bean scope allows Web application to have bean instance per session basis. both of these bean scope are available on WebApplicationContext or any web aware application context. Last one which is global session bean scope is only applicable on portlet aware bean scope and allows bean instance per global session. In short Singleton vs prototype is an important which clearly segregate one instance to multiple instances of bean.

How to specify Bean Scope in Spring Framework

In order to specify bean scope you can either use Annotation on Spring or you can define it on Application Context, for example in below Spring configuration file AuditService is configured as Singleton using singleton bean scope and PaymentService as prototype bean scope.

//bean configured on singleton bean scope
<bean id="auditService" class="com.sample.service.impl.AuditServiceImpl"  scope="singleton"/>

Since singleton is also default scope in spring framework, following declaration is exactly same and creates bean on singleton scope.

<bean id="auditService" class="com.sample.service.impl.AuditServiceImpl" />

Though I prefer explicit declaration to make bean scope loud and clear. Now every time you call getBean("auditService") it will return same instance of AuditService.

AuditService auditService = ApplicationContext.getBean("auditService");

//bean configured on prototype bean scope
<bean id="auditService" class="com.sample.service.impl.AuditServiceImpl"  scope="prototype"/>


In case of prototype beans cope every call to getBean("auditServie") will return different instance of AuditServiceImpl class. If you want to use Annotation to define bean scope than you can use @Scope("singleton") or @Scope("prototype") on Bean class. you will also need to enable component scanning in Order to let Spring knows about bean scope. which you can do it spring 2.5 as <context:component-scan base-package="com.sample.service.impl" />. Bean scope has not been changed from various spring version and so far two most used spring version spring 2.5 and spring 3.0 has only five bean scope.

Bean Scope in Spring 2.5 and Spring 3.0 is similar, all default scopes are still supported in spring 3.0 with addition of few new scopes like thread scope or SimpleThreadScope  which is a scope backed by thread. You can also register your own custom scope using CustomScopeConfigurer utility., there is no new scope for bean is introduced on spring 3.0

That’s about what is bean scope in Spring framework. Since bean creation is managed by Spring IOC container its worth remember that how to specify scope for a particular Bean and what is default scope of Bean which is Singleton to avoid any assumption and code accordingly.

Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using mock object. So, for example, if you have service class

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.     Describe synchronization in respect to multithreading. With respect to

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an argument. Lets see how to convert list to Set using java program.