Spring scope
Chapter 1. Spring Singleton scope
In this article, I will explain: what does “The Spring scope” means, how to use it, how it works behind closed doors, and in which use-case scenarios should we use those.
At the beginning of the article, ı wanted to collect all the scope types in this article. As I explored the finer details on scopes, the article started to get longer. Therefore, I decided to go to pieces the article into sections.
Let’s begin:
Bean Scopes
We know the concept of spring bean. What will happen to the beans after producing these beans? How will the life journey of the created bean continue? Will it be stored ram and then reused? Or will a new one occur in the new request? What will be the life cycles of these formed beans? The mechanism that answers these questions is called “spring scope”.Let’s examine the struggle for survival of these spring beans with a documentary taste. :)
Spring Bean Scopes are managed by the Spring Ioc container. The latest version of the Spring framework defines 6 types of scopes.
- singleton
- Prototype
- Request
- Session
- Application
- WebSocket
Scope Types
1. Singleton scope
The singleton scope is the default scope in spring.
Definition: When we want to define a singleton bean Spring Ioc Container will define one of the defined objects and store it in the cache. When we want to any action for this bean, it will return the object stored in the cache to us every time. When we want to create another one from the same bean, the object it will return to us will be the same.
Let’s give the stereotypical “DatabaseConnection” example when we hear the word “SINGLETON”. After doing this sacred ritual, different examples reinforce “SINGLETON SCOPE”. :) :)
Image: We wanna make a database connection. Therefore this we have to create a bean. But it’s enough to connect with the same bean every time. Because we need to connect to the database with the same connection every time. That’s why we need to create singleton a bean.
The use-Case scenario of Singleton Scope in real life
Scenario:
We created a task in our application. A use wrote the content of the task, titled it, and took ownership of the task. Then another user changed the title of the task. Then again someone else came and found the content missing and changed it. Then they assigned it to themselves again. Assume these transactions are done in a row and by many users.
So how have we managed these processes in the background?
For instance, we instantiate the task class and when users want to do something, we pull a task from the database. After the process is done send the database and update the task class. What a tedious process, right? Going to and from the database every time.
Well !!!. try this in singleton scope.
It’s a big cost to go back and forth from the database every time.
We created a bean for a task class and made it the default singleton type. When we create one of these beans, the Ioc container keeps it cached and returns us the same bean every time. When users want to update task bean. Ioc container returned the same bean. And we updated this without needing to create a new bean.
If we understand the example, we can now code it.
Bean.xml
Task class
API URL for postman =>
http://localhost:8080/api2/createTaskBean
http://localhost:8080/api2/updateTaskBean
Talk a little bit about our code.
First of all, task class created, then taskBean.xml and set singleton type (Should not do this because we said the default state is a singleton)
We finally Autowired the ApplicationContext in-service class. Bean is created in create method and necessary properties are set. In the update method, “the same bean is created in the same container” is called and updated.
Let’s see what is written in the console when ı trigger the first and second API in the postmen.
Created and up updated the same bean cached as you follow the beacons.
Question: So what would happen if called the update first and then create the method?
It gave the above error because we wanted to update non created bean.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘taskId’ available
Let’s try something more
Question: if it created more than one task bean, then which bean would the update-method update
Let’s try,
The last bean that occurred has been updated.
So why did it happen? Because we said we can create only one bean in a Spring singleton, you can create as many beans you want from the same container. A valid bean will be the last creature.
İmprotant Note:
Please be aware that Spring’s concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hard codes the scope of an object such that one and only one instance of a particular class will ever be created per
ClassLoader
. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring.
Let’s examine what the above paragraph means with an example question that will give below. For this, firstly update the task bean.xml file as follows.
What does the console write when the above code runs? True? False?
false
com.example.springscope.controller.Task@6d64b553::com.example.springscope.controller.Task@53667cbe
True answers are a “False”.
Because Spring Ioc container creates a bean instance and returns that's a bean to when calling it. When creating a second bean from the same class, the second bean is also stored in a cache it and it returns an instance bean when we call it.
In chapter 1 of this article, I explained “the spring singleton scope”, In chapter 2 ı am going to explain “Prototype scope”.