i'm new to spring and i read this :
Basically a bean has scopes which defines their existence on the application
Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
So What is the "object instance" .
You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.
The difference is that Spring will clean up singleton beans and destroy them once the containing application context is destroyed. That means that a singleton bean will remain in your JVM memory unless the application context is shutdown or if the bean is manually destroyed.
But why singleton? When a service is stateless, it's thread-safe, and it can scale to any number of concurrent requests, so there's no need for a second copy of the same service. Unlike EJB, where there's stateful and stateless beans, Spring has only one type of bean: stateless.
When you work with a prototype bean in a singleton, you have three options to get a new instance of the prototype: Spring can autowire a single prototype instance when it creates the singleton. It's the default framework behavior. Spring can create a new prototype instance on every call to any method of this prototype.
Prototype scope = A new object is created each time it is injected/looked up. It will use new SomeClass()
each time.
Singleton scope = (Default) The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeClass
and then return it each time.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With