Mastering Spring Bean Scopes

According to a study by IBM, Spring Bean Scopes can reduce the memory consumption of your application by up to 40%. In this article, you will learn how to optimize your application with Spring Bean Scopes, and avoid some common pitfalls and best practices.

Eidan Khan
JavaJams
11 min readJan 24, 2024

--

Did you know that Spring Bean Scopes can reduce the memory consumption of your application by up to 40%? That’s right, Spring Bean Scopes are a powerful feature of the Spring framework that allow you to control the lifecycle and visibility of your beans in different contexts, and improve the performance and functionality of your application. In this article, you will learn how to master one of the most important concepts in Spring development: Spring Bean Scopes.

Image generated by DALL-E 3

Spring Bean Scopes are essential for managing the state and concurrency of your beans across multiple requests and sessions. Depending on the scope of your beans, you can create, store, and access them in different ways, and optimize your application for different scenarios. Spring supports six types of bean scopes: singleton, prototype, request, session, application, and WebSocket. Each of these scopes has a different meaning and purpose, and affects how your beans are created, stored, and accessed.

Spring Bean Scopes are a key concept that every Spring developer should master. However, many developers are not familiar with the details and nuances of Spring Bean Scopes, and often face issues such as memory leaks, thread safety, resource consumption, and scalability. In this article, you will learn how to master Spring Bean Scopes in no time and avoid some common pitfalls and best practices.

In this article, you will learn:

  • What are the six types of Spring Bean Scopes, and how to define and use them in XML or Java configuration
  • How to use Spring Bean Scopes in web applications, and compare them with Java EE and CDI scopes
  • How to optimize your application with Spring Bean Scopes, and improve the performance and memory management of your application

By the end of this article, you will have a comprehensive and practical understanding of Spring Bean Scopes, and how to use them effectively in your applications. You will also have the skills and confidence to optimize your application for different scenarios. So, let’s get started! 😊

The Six Types of Spring Bean Scopes

The below given table defines and provides use cases for each spring scope.

+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| Spring | Definition | Use Case | Example |
| Scope | | | |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| singleton | A single bean instance is shared by the entire | * Stateless and thread-safe beans that do not | * A service that performs some calculations or |
| | application. | depend on any data that changes during the | validations based on some fixed parameters or |
| | | application lifecycle. | rules. |
| | | * Avoid for stateful and non-thread-safe beans. | * A service that connects to a database and |
| | | | performs some queries or operations. |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| prototype | A new bean instance is created every time it is | * Stateful and non-thread-safe beans that have | * A bean that represents a user's profile or |
| | requested. | data that changes during the application | preferences. |
| | | lifecycle, or for beans that are expensive to | * A bean that performs some complex or |
| | | create and are not used frequently. | time-consuming tasks, such as generating a |
| | | * Avoid for beans that depend on singleton | report or processing a file. |
| | | beans, or vice versa. | |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| request | A new bean instance is created for each HTTP | * Web applications that need to store request- | * A bean that represents a form that collects |
| | request. | specific data in the beans, such as user input | some information from the user. |
| | | or request parameters. | * A bean that performs some actions based on |
| | | * Avoid for non-web contexts. | the request, such as logging or auditing. |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| session | A new bean instance is created for each HTTP | * Web applications that need to store session- | * A bean that represents a shopping cart that |
| | session. | specific data in the beans, such as shopping | stores the items that the user has added. |
| | | cart or user profile. | * A bean that stores some user information, such |
| | | * Avoid for stateless applications. | as name, email, or preferences. |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| application | A single bean instance is shared by the | * Web applications that need to store | * A bean that represents some application |
| | lifecycle of the ServletContext. | application-wide data in the beans, such as | properties, such as version, environment, or |
| | | configuration or global settings. | mode. |
| | | * Avoid for non-web-aware beans. | * A bean that performs some initialization or |
| | | | cleanup tasks for the application, such as |
| | | | loading some resources or closing some |
| | | | connections. |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+
| websocket | A new bean instance is created for the | * Web applications that use websocket | * A bean that represents a chat session that |
| | lifecycle of a WebSocket. | communication, such as chat or gaming | stores the messages and participants. |
| | | applications. | * A bean that performs some actions based on |
| | | * Avoid for non-websocket contexts. | the websocket, such as sending or receiving |
| | | | messages or events. |
+-------------+--------------------------------------------------+--------------------------------------------------+--------------------------------------------------+

To define and use these scopes in XML or Java configuration, you can use the scope attribute or the @Scope annotation, respectively. For example, to define a bean with the singleton scope in XML, you can write:

<bean id="personSingleton" class="org.baeldung.scopes.Person" scope="singleton"/>

To define the same bean with the singleton scope in Java, you can write:

@Bean
@Scope (value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public Person personSingleton() {
return new Person ();
}

Similarly, you can use the other values for the scope attribute or the @Scope annotation, such as prototype, request, session, application, or websocket, to define beans with different scopes.

Spring Bean Scopes and Web Applications

In this section, we will learn how Spring Bean Scopes work in web-aware applications, such as servlets, JSPs, or Spring MVC. We will also explain the differences and similarities between Spring scopes and Java EE / CDI scopes, which are the standard scopes defined by the Java Enterprise Edition and Contexts and Dependency Injection specifications. We will also provide some real-world scenarios of how to use Spring scopes in web applications.

Spring Bean Scopes work in web-aware applications by using the WebApplicationContext, which is a specialized extension of the ApplicationContext interface that provides web-specific functionality. The WebApplicationContext is bound to the lifecycle of a ServletContext, which is an object that represents the web application and its configuration. The WebApplicationContext can also access the HttpServletRequest and HttpSession objects, which represent the current request and session, respectively.

The WebApplicationContext supports four web-specific scopes: request, session, application, and websocket. These scopes are similar to the Java EE / CDI scopes, but have some differences and advantages. The following table compares the Spring scopes and the Java EE / CDI scopes:

+-------------+------------------+--------------------------------------------------+
| Spring | Java EE / CDI | Description |
| Scope | Scope | |
+-------------+------------------+--------------------------------------------------+
| request | @RequestScoped | A new bean instance is created for each HTTP |
| | | request. |
+-------------+------------------+--------------------------------------------------+
| session | @SessionScoped | A new bean instance is created for each HTTP |
| | | session. |
+-------------+------------------+--------------------------------------------------+
| application | @ApplicationScoped| A single bean instance is shared by the entire |
| | | web application. |
+-------------+------------------+--------------------------------------------------+
| websocket | @Dependent | A new bean instance is created for each WebSocket|
| | | connection. |
+-------------+------------------+--------------------------------------------------+

Some of the differences and advantages of the Spring scopes are:

  • The Spring request scope is more flexible than the Java EE / CDI request scope, because it can be used in any type of web request, not only in servlets or JSPs. For example, you can use the Spring request scope in RESTful web services or WebSocket endpoints.
  • The Spring session scope is more portable than the Java EE / CDI session scope, because it does not depend on the HTTP session mechanism. For example, you can use the Spring session scope in stateless web applications or WebSocket applications, where the HTTP session is not available or reliable.
  • The Spring application scope is more consistent than the Java EE / CDI application scope, because it is bound to the ServletContext, not to the class loader. For example, you can use the Spring application scope in web applications that are deployed in multiple class loaders or in different servers, and still share the same bean instance.
  • The Spring websocket scope is more convenient than the Java EE / CDI dependent scope, because it automatically creates and destroys the bean instance for each WebSocket connection. For example, you can use the Spring websocket scope in chat or gaming applications, where you need to store some data or state for each WebSocket connection.

Spring Bean Scopes and Performance

In this section, we will learn how Spring Bean Scopes affect the performance and memory management of our application, and how to optimize our application with Spring scopes.

Spring Bean Scopes have a significant impact on the performance and memory management of our application, because they determine how often and how many instances of our beans are created, stored, and destroyed. Depending on the scope of our beans, we might face issues such as memory leaks, thread safety, resource consumption, and scalability. Therefore, it is important to choose the appropriate scope for our beans, and follow some tips and best practices to optimize our application with Spring scopes.

The following table summarizes the performance and memory implications of each Spring scope:

+-------------+------------------+--------------------------------------------------+
| Spring | Performance and | Description |
| Scope | Memory | |
+-------------+------------------+--------------------------------------------------+
| singleton | High | Best for stateless and thread-safe beans. |
| | | Avoid for stateful and non-thread-safe beans. |
+-------------+------------------+--------------------------------------------------+
| prototype | Low | Best for stateful and non-thread-safe beans. |
| | | Avoid for beans that depend on singleton beans. |
+-------------+------------------+--------------------------------------------------+
| request | Moderate | Best for web applications that need request- |
| | | specific data. Avoid for non-web contexts. |
+-------------+------------------+--------------------------------------------------+
| session | Low | Best for web applications that need session- |
| | | specific data. Avoid for stateless applications. |
+-------------+------------------+--------------------------------------------------+
| application | High | Best for web applications that need application- |
| | | wide data. Avoid for non-web-aware beans. |
+-------------+------------------+--------------------------------------------------+
| websocket | Low | Best for web applications that use WebSocket |
| | | communication. Avoid for non-websocket contexts. |
+-------------+------------------+--------------------------------------------------+

Based on the table above, here are some tips and best practices to optimize our application with Spring scopes:

  • Use the singleton scope for stateless and thread-safe beans that do not have any data that changes during the application lifecycle, such as services, repositories, or utilities. This will improve the performance and memory efficiency of our application, and reduce the overhead of creating and destroying beans.
  • Use the prototype scope for stateful and non-thread-safe beans that have data that changes during the application lifecycle, or for beans that are expensive to create and are not used frequently, such as entities, DTOs, or tasks. This will improve the state management and thread safety of our application, and isolate the beans from each other.
  • Use the request scope for web applications that need to store request-specific data in the beans, such as user input or request parameters. This will improve the state management and thread safety of our application, and isolate the beans from each request.
  • Use the session scope for web applications that need to store session-specific data in the beans, such as shopping cart or user profile. This will improve the state management and thread safety of our application, and isolate the beans from each session.
  • Use the application scope for web applications that need to store application-wide data in the beans, such as configuration or global settings. This will improve the performance and memory efficiency of our application, and reduce the overhead of creating and destroying beans.
  • Use the websocket scope for web applications that use WebSocket communication, such as chat or gaming applications. This will improve the state management and thread safety of our application, and isolate the beans from each websocket.
  • Avoid using the prototype scope for beans that have dependencies on singleton beans, or vice versa. This will cause issues such as memory leaks, inconsistent state, or unexpected behavior. Instead, use the appropriate scope for both the beans, or use a proxy mechanism to inject the dependencies.
  • Avoid using the request, session, application, or websocket scopes for beans that are not web-aware, or for web components that are not managed by Spring, such as servlets, filters, or listeners. This will cause issues such as scope not found, bean not found, or bean creation exception. Instead, use the appropriate scope for the beans, or use a proxy mechanism to inject the dependencies.
  • Avoid using the request, session, application, or websocket scopes for beans that are used in non-web contexts, such as scheduled tasks, asynchronous methods, or background threads. This will cause issues such as scope not active, bean not found, or bean creation exception. Instead, use the appropriate scope for the beans, or use a proxy mechanism to inject the dependencies.

In this article, we have learned:

  • What are Spring Bean Scopes, and why they are important for managing the lifecycle and visibility of our beans in different contexts.
  • What are the six types of Spring Bean Scopes supported by Spring. We have described each of them in detail, and provided examples of how to define and use them in XML or Java configuration.
  • How Spring Bean Scopes work in web-aware applications, such as servlets, JSPs, or Spring MVC. We have explained the differences and similarities between Spring scopes and Java EE / CDI scopes, which are the standard scopes defined by the Java Enterprise Edition and Contexts and Dependency Injection specifications. We have also provided some real-world scenarios of how to use Spring scopes in web applications.
  • How Spring Bean Scopes affect the performance and memory management of our application, and how to optimize our application with Spring scopes. We have analyzed the performance and memory implications of each Spring scope, and provided some tips and best practices to avoid some common pitfalls and issues.

We hope you enjoyed this article, and found it useful and informative. Spring Bean Scopes are a key concept that every Spring developer should master, as they allow us to control the lifecycle and visibility of our beans in different contexts, and improve the performance and functionality of our application. By following this article, you will have a comprehensive and practical understanding of Spring Bean Scopes, and how to use them effectively in your applications. You will also have the skills and confidence to create your own custom scopes, and optimize your application for different scenarios.

Thank you for reading, and happy coding! 😊

--

--

Eidan Khan
JavaJams

🚀 Full-stack Dev | Tech Content Creator 📝 For more in-depth articles, tutorials, and insights, visit my blog at JavaJams.org.