0
votes

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?

3
I'd be careful with this idea. In some frameworks, beans can move from server to server (one "server" might actually be a cluster of servers). In that case it might no longer be true that you have a single object that is literally being shared by all threads in a system.markspace
@markspace Even in Spring, singleton beans are only singleton within the application context (instance). Scale 4 instances, you have 4 copies.chrylis -cautiouslyoptimistic-
I thought as much. I just wanted to make sure the OP was aware of all possibilities, just in case it affected their design.markspace

3 Answers

1
votes

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?

1
votes

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

0
votes

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