Friday, April 26, 2024

What is bean scope in Spring Framework? Example Tutorial

Java classes or POJO which are managed by Spring Framework are called Bean or Spring Beans and Bean scope in Spring framework or Spring MVC is scope for a bean managed by Spring IOC container. Bean scope refers to the lifecycle and visibility of a bean instance in spring container. The scope determines how long the bean instance will live and how it will be shared with the other parts of application. You may know that Spring is a framework that 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 the Spring framework. Spring allows you to define how those beans will be created and the scope of the bean is one of those details. Scope are similar to access modifiers in Java which specifies visibility of a particular class. 


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

1) Singleton (default scope)
2) prototype
3) request
4) session
5) global-session
6) Application
7) WebSocket scope
8) Custom scope

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

Similarly, Application and web socket scopes are also not standard and they are introduced by the framework which integrates with Spring like Spring WebFlux and Spring Web MVC

WebSocket scope is similar to session scope but it applies to web socket session in a web socket enabled application. On other hand, Application scope ties the lifecycle of a bean with the lifecycle of a servlet context in a Java web application.

A single instance of the bean is created in application scope for entire duration of application and its shared between all requests. 


By the way, if you are new to Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at Spring Framework 6: Beginner to Guru, one of the comprehensive and hands-on course to learn modern Spring. It' also most up-to-date and covers Spring 6. 

Now, let's understand both singleton and prototype bean scope in more detail. 




5 Bean Scopes in Spring framework with Example

Singleton 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 a Singleton pattern in Java where only one instance of the bean is created per Spring container. 

So no matter how many times you call getBean() method, the same bean instance will be returned if its bean scope is declared as Singleton.

While in the case of prototype bean scope, every getBean() call creates a new instance of Spring bean. The 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 a bean created and supplied by Spring framework, while session bean scope allows a Web application to have bean instance per session basis. Both of these bean scopes are available on WebApplicationContext or any web-aware application context.

The Last one which is global session bean scope is only applicable to portlet aware bean scope and allows bean instance per global session. In short singleton vs prototype is important which clearly segregates one instance to multiple instances of bean. 

The newly added Application and WebSocket scope are for Spring WebFlux and Spring Web MVC. Application scope bean is created once and ties with servlet context for entire duration of application and same bean is shared with all request. 

This means you bean must be thread-safe since its shared with all the request, otherwise it could cause multithreading and concurrency issue. 

As I said earlier, Web Socket scope is like session scope but its for web socket session and its only application for web socket enabled application. 

Many programmer doesn't know but Spring also allows developer to create their own bean scope by implementing org.springframework.bean.factory.config.Scope interface.  

Custom scopes can be really useful in scenarios when standard scope are not enough for example creating a transaction scope which allows bean to live for a transaction, a conversational scope, a cache scope, a tenant scope which can be used in multi-tenant application where bean is scoped with a specific tenant and its not shared between tenants or isolated between tenants. 

If you are interested to learn more about Spring basics, you can also check out Spring Framework: Spring Fundamentals course on Pluralsight by Bryan Hansen. It's nice course to learn essential Spring concepts in 2 and half hours. 

What is Bean scope in Spring MVC framework with Example





How to specify Bean Scope in Spring Framework?

bean scope in Spring 2.5 and spring 3.0In 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 the spring framework, the following declaration is exactly the 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 the 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 the case of the prototype, beans cope every call to getBean("auditServie") will return different instances 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 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 5 and spring 6.0 has only five bean scope.

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

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

A good knowledge of bean scope is essential to write a robust and safe spring based application as choosing a incorrect bean scope may cause concurrency and caching issues. It's also essential to effectively manage dependencies and resource usage within Spring boot application. 



Other Java tutorials you may like

References


P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join the Learn Spring: The Certification Class by Eugen Paraschiv. One of the best courses to learn Spring 5 and Spring Boot 2 from scratch, in a guided, code-focused way.

4 comments:

  1. Or since Spring 3.0 you can use standard annotations JSR-330 (known as @Inject), that were introduced in Java EE 6. There's also annotation @Scope, but singleton is defined using annotation @Singleton.

    ReplyDelete
  2. What is default bean Scope in Spring 3.0? Singleton scope ?? Is there any way we can change default bean Scope to prototype or request ?

    ReplyDelete
  3. i want to know how can i restrict the no of bean objects to be created for a spring bean to 50.

    ReplyDelete
  4. Hi....

    Thanks for your awesome tutorials, gained lot of information!!
    I was asked in an interview, we know that the default bean scope in Spring is Singleton, why is it so?
    i am totally stuck, not able to find why, can you please help me?

    TIA

    ReplyDelete