Sunday, 10 April 2016

Prototype vs Request bean scope in Spring

prototype: This bean scope just reverses the behavior of singleton scope and produces a new instance each and every time a bean is requested.

request: Only one instance is created for an HttpRequest.
With this bean scope, a new bean instance will be created for each web request made by client. As soon as request completes, bean will be out of scope and garbage collected.

HttpRequest or request scope
For a in a single HttpRequest, when we will call getBean twice on Application and there will ever be one bean instantiated, whereas that same bean scoped to Prototype in that same single HttpRequest would get 2 different instances.

     MyBean myBean1 = context.getBean("myBean");
     MyBean myBean2 = context.getBean("myBean");
     myBean1 == myBean2; //This will return true

prototype scope
Prototype creates a brand new instance every time when we call getBean on the ApplicationContext.

     MyBean myBean1 = context.getBean("myBean");
     MyBean myBean2 = context.getBean("myBean");
     myBean1 == myBean2; //This will return false.


How to define the bean scope

1) In bean configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      
    <bean id="myBean" class="com.MyBean" scope="session"/>
      
</beans>

2) Using annotations

@Service
@Scope("session")
public class MyBean {
     //Some code
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...