I am thinking about @scope("prototype") scope but I don't get it because we already have the new keyword. Both of them create a new instance of an object in runtime. What is the advantage of using prototype? Is it easier to reallocate than using new? Am I doing something wrong when I create new object with using the new keyword?
I'm trying to understand the advantages of it.
I found this question but it does not explain the advantages / disadvantages of new and prototype: What is the difference between bean with scope prototype and new Object in singleton bean?
By using new keyword you are creating an java object but it is not a spring bean and will not present in spring container. But if you use @scope("prototype") for every request a new spring bean is provided. for more information
What is a spring bean?
A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in a Spring configuration file (or, more recently, by using annotations), instantiated by the Spring container, and then injected into your application.
Advantages of spring bean?
1) By default all spring beans are immutable and spring IOC container will manage them
2) By using dependency injection you can inject the beans into any other object easily
3) Dependency injection makes testing easier. The injection can be done through constructor.
4) If you are using spring boot then you can inject the values from application.yml or application.properties into spring beans by using @Value annotation
Its straightforward. In some scenarios you might need separate instance in every bean. It is almost equal to creating with new when needed with an exception that you have the ability to inject dependencies to whatever you have marked as prototype.
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