1. Overview:

As per Spring documentation Spring Bean’s definition isIn Spring the objects that form the backbone of your application project and that are managed by the Spring IoC container are called Beans.” The scope is a Bean attribute which is used to define what kind of instance should create and return when called.

2. Types of Scopes:

There are 5 types of Bean scopes available in Spring. Spring enables support of WebSocket and introduces a new scope WebSocket scope in web-aware spring configuration.

2.1 Valid in any configuration

    1. Singleton scope
    2. Prototype scope

2.2 Valid only in web-aware Spring configuration

    1. Request scope
    2. Session scope
    3. Global session scope
    4. WebSocket scope

3. Singleton Scope:

Singleton is default bean scope this means that there will be only one instance per Spring container. If there is no scope configuration given to a bean than it will be treated as Singleton. In Singleton scope, there will be only one instance per Spring container.

[Note: there can be multiple Spring container in JVM]

Example: 

Using XML Base Configuration

Spring-Customer.xml:

<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.xsd">
 
   <bean id="scopeDemoService" class="com.javadeveloperzone.ScopeDemoService" scope="singleton"/>
 
</beans>

Using the Annotation/java base configuration:

package com.javadeveloperzone;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(value= BeanDefinition.SCOPE_SINGLETON)
public class ScopeDemoService
{
  private String message;
  public String getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

Output: 

ScopeDemoApp.java:
package com.javadeveloperzone;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeDemoApp
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
    		new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
    	ScopeDemoService serviceA = (ScopeDemoService)context.getBean("scopeDemoService");
    	System.out.println("ServiceA Object : " + serviceA);
    	
    	//retrieve it again
    	ScopeDemoService serviceB = (ScopeDemoService)context.getBean("scopeDemoService");
    	System.out.println("ServiceB Object : " + serviceB);
    }
}

Console:

ServiceA Object: [email protected]
ServiceB Object: [email protected]

As shown in the output there is the same instance returned by different getBean call this means that there is only one instance per IoC container no matter how many times we retrieve it.

4. Prototype Scope

Prototype Scope returns one instance per request. It will be a guaranteed unique instance per bean request. Prototype scope is the opposite of a singleton bean scope.

Example: 

Spring-Customer.xml:

<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.xsd">
 
   <bean id="scopeDemoService" class="com.javadeveloperzone.ScopeDemoService" scope="prototype"/>
 
</beans>

Using the Annotation/java base configuration:

ScopeDemoService.java
package com.javadeveloperzone;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(value= BeanDefinition.SCOPE_PROTOTYPE)
public class ScopeDemoService
{
  private String message;
  public String getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

Output:

ScopeDemoApp.java:
package com.javadeveloperzone;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ScopeDemoApp
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
    		new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});
 
    	ScopeDemoService serviceA = (ScopeDemoService)context.getBean("scopeDemoService");
    	System.out.println("ServiceA Object : " + serviceA);
    	
    	//retrieve it again
    	ScopeDemoService serviceB = (ScopeDemoService)context.getBean("scopeDemoService");
    	System.out.println("ServiceB Object : " + serviceB);
    }
}

Console:

ServiceA Object: [email protected]
ServiceB Object: [email protected]

As shown in the output there is a new unique instance per getBean request.

5. A brief overview of a scope which is valid only on a web-aware Spring project

 As we have shown in the type of scopes 4 scopes are available in web-aware spring configuration only. Following is basic briefing about them 

  • Request scope:

    • In the Request scope, there will be a new bean instance per Http Request.
    • In java configuration, @RequestScope annotation is used to define request scope
  • Session scope:

    • In the Session scope, there will be a single bean instance per Http Session
    • In java configuration, @SessionScope annotation is used to define session scope 
  • GlobalSession scope:

    • In the Global session scope, there will be a single bean per Application.
    • GlobalSession scope can be define by @Scope (value = WebApplicationContext.SCOPE_GLOBAL_SESSION) in java configuration
  • WebSocket scope:

    • WebSocket protocol enables two-way communication between client and server.
    • WebSocket scope creates a bean per WebSocket session.
    • WebSocket scope can be define by @Scope (name = “websocket”) in java configuration.
    • WebSocket-scoped beans can be injected into controllers and any channel interceptors registered on the “clientInboundChannel”. Those are typically singletons and live longer than any individual WebSocket session. Therefore, you will need to use a scope proxy mode for WebSocket-scoped beans @Scope (name = “websocket”, proxyMode = ScopedProxyMode.TARGET_CLASS)

6. Conclusion:

In this article, we have discussed Spring bean scopes. we have given brief details about Singleton and prototype scope and basic overview about scopes that are available only in a web-aware project we have also given a basic overview of the latest scope introduce by Spring that is WebSocket scope.

7. References

 

Was this post helpful?

Leave a Reply

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