Nichole
Nichole

Reputation: 219

Do multiple thread request share same singleton beans in Spring?

I have been trying to understand spring beans. As per my understanding, by default all beans are singleton and a singleton bean with lazy-init property set to true is created when it is first requested and singleton bean with lazy-init property set to false is created when the application context is created.

So, in an application, when a user request comes in ( where each request is a separate thread), do all these threads share the same singleton beans when requested within the program/class?

Upvotes: 2

Views: 4976

Answers (3)

Yusuf BESTAS
Yusuf BESTAS

Reputation: 194

The best way to understand this is to understand how @Autowired annotation works. Or in other words to understand "Spring Dependency Injection".

You said, "

by default all beans are singleton

We use @Autowired when injecting one layer into another between two layers.

If exemplify: Suppose, I want to inject UserService UserController. UserService is a Singleton bean. Creates an instance from UserService and Stores its cache. When we want to inject this service with @Autowired annotation. This annotation brings the UserService stored in the cache.

In this way, Even if we do this inject operation in many classes.@Autowired inject an instance of UserService with singleton bean instead of dealing with one UserService at each time. It saves us a big burden. This is the fundamental working logic of Spring Singleton Bean.

Also, Spring Ioc Container manages this whole process.

enter image description here

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23089

Yes, by default (scope == 'singleton'), all threads will share the same singleton bean. There are two other bean scopes, session and request, that may be what you're looking for. The request scope creates a bean instance for a single HTTP request while session scope maintains a unique bean for each HTTP Session.

For a list and description of all of the Spring bean scopes, check out: Spring bean scopes

Upvotes: 1

Dragos Ionut
Dragos Ionut

Reputation: 257

Yes, if the bean is created with default scope, the bean is shared across threads. However, another scope can be used to achieve the behaviour you mentioned. See: https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html?

Upvotes: 1

Related Questions